home *** CD-ROM | disk | FTP | other *** search
/ Languguage OS 2 / Languguage OS II Version 10-94 (Knowledge Media)(1994).ISO / gnu / bash_114.zip / bash-1.14.2 / execute_cmd.c < prev    next >
C/C++ Source or Header  |  1994-08-04  |  100KB  |  3,676 lines

  1. /* execute_command.c -- Execute a COMMAND structure. */
  2.  
  3. /* Copyright (C) 1987,1991 Free Software Foundation, Inc.
  4.  
  5.    This file is part of GNU Bash, the Bourne Again SHell.
  6.  
  7.    Bash is free software; you can redistribute it and/or modify it
  8.    under the terms of the GNU General Public License as published by
  9.    the Free Software Foundation; either version 1, or (at your option)
  10.    any later version.
  11.  
  12.    Bash is distributed in the hope that it will be useful, but WITHOUT
  13.    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  14.    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  15.    License for more details.
  16.  
  17.    You should have received a copy of the GNU General Public License
  18.    along with Bash; see the file COPYING.  If not, write to the Free
  19.    Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
  20. #if defined (AIX) && defined (RISC6000) && !defined (__GNUC__)
  21.   #pragma alloca
  22. #endif /* AIX && RISC6000 && !__GNUC__ */
  23.  
  24. #include <stdio.h>
  25. #include <ctype.h>
  26. #include "bashtypes.h"
  27. #include <sys/file.h>
  28. #include "filecntl.h"
  29. #include "posixstat.h"
  30. #include <signal.h>
  31.  
  32. #if !defined (SIGABRT)
  33. #define SIGABRT SIGIOT
  34. #endif
  35.  
  36. #include <sys/param.h>
  37. #include <errno.h>
  38.  
  39. #if !defined (errno)
  40. extern int errno;
  41. #endif
  42.  
  43. #if defined (HAVE_STRING_H)
  44. #  include <string.h>
  45. #else /* !HAVE_STRING_H */
  46. #  include <strings.h>
  47. #endif /* !HAVE_STRING_H */
  48.  
  49. #include "shell.h"
  50. #include "y.tab.h"
  51. #include "flags.h"
  52. #include "hash.h"
  53. #include "jobs.h"
  54. #include "execute_cmd.h"
  55.  
  56. #include "sysdefs.h"
  57. #include "builtins/common.h"
  58. #include "builtins/builtext.h"    /* list of builtins */
  59.  
  60. #include <glob/fnmatch.h>
  61. #include <tilde/tilde.h>
  62.  
  63. #if defined (BUFFERED_INPUT)
  64. #  include "input.h"
  65. #endif
  66.  
  67. extern int posixly_correct;
  68. extern int breaking, continuing, loop_level;
  69. extern int interactive, interactive_shell, login_shell;
  70. extern int parse_and_execute_level;
  71. extern int command_string_index, variable_context, line_number;
  72. extern int dot_found_in_search;
  73. extern char **temporary_env, **function_env, **builtin_env;
  74. extern char *the_printed_command, *shell_name;
  75. extern pid_t last_command_subst_pid;
  76. extern Function *last_shell_builtin, *this_shell_builtin;
  77. extern jmp_buf top_level, subshell_top_level;
  78. extern int subshell_argc;
  79. extern char **subshell_argv, **subshell_envp;
  80. extern int already_making_children;
  81.  
  82. extern int getdtablesize ();
  83. extern int close ();
  84.  
  85. /* Static functions defined and used in this file. */
  86. static void close_pipes (), do_piping (), execute_disk_command ();
  87. static void execute_subshell_builtin_or_function ();
  88. static void cleanup_redirects (), cleanup_func_redirects (), bind_lastarg ();
  89. static void add_undo_close_redirect (), add_exec_redirect ();
  90. static int do_redirection_internal (), do_redirections ();
  91. static int expandable_redirection_filename (), execute_shell_script ();
  92. static int execute_builtin_or_function (), add_undo_redirect ();
  93. static char *find_user_command_internal (), *find_user_command_in_path ();
  94.  
  95. /* The line number that the currently executing function starts on. */
  96. static int function_line_number = 0;
  97.  
  98. /* Set to 1 if fd 0 was the subject of redirection to a subshell. */
  99. static int stdin_redir = 0;
  100.  
  101. /* The name of the command that is currently being executed.
  102.    `test' needs this, for example. */
  103. char *this_command_name;
  104.  
  105. struct stat SB;        /* used for debugging */
  106.  
  107. static REDIRECTEE rd;
  108.  
  109. /* For catching RETURN in a function. */
  110. int return_catch_flag = 0;
  111. int return_catch_value;
  112. jmp_buf return_catch;
  113.  
  114. /* The value returned by the last synchronous command. */
  115. int last_command_exit_value = 0;
  116.  
  117. /* The list of redirections to perform which will undo the redirections
  118.    that I made in the shell. */
  119. REDIRECT *redirection_undo_list = (REDIRECT *)NULL;
  120.  
  121. /* The list of redirections to perform which will undo the internal
  122.    redirections performed by the `exec' builtin.  These are redirections
  123.    that must be undone even when exec discards redirection_undo_list. */
  124. REDIRECT *exec_redirection_undo_list = (REDIRECT *)NULL;
  125.  
  126. /* Non-zero if we have just forked and are currently running in a subshell
  127.    environment. */
  128. int subshell_environment = 0;
  129.  
  130. struct fd_bitmap *current_fds_to_close = (struct fd_bitmap *)NULL;
  131.  
  132. #define FD_BITMAP_DEFAULT_SIZE 32
  133. /* Functions to allocate and deallocate the structures used to pass
  134.    information from the shell to its children about file descriptors
  135.    to close. */
  136. struct fd_bitmap *
  137. new_fd_bitmap (size)
  138.      long size;
  139. {
  140.   struct fd_bitmap *ret;
  141.  
  142.   ret = (struct fd_bitmap *)xmalloc (sizeof (struct fd_bitmap));
  143.  
  144.   ret->size = size;
  145.  
  146.   if (size)
  147.     {
  148.       ret->bitmap = xmalloc (size);
  149.       bzero (ret->bitmap, size);
  150.     }
  151.   else
  152.     ret->bitmap = (char *)NULL;
  153.   return (ret);
  154. }
  155.  
  156. void
  157. dispose_fd_bitmap (fdbp)
  158.      struct fd_bitmap *fdbp;
  159. {
  160.   FREE (fdbp->bitmap);
  161.   free (fdbp);
  162. }
  163.  
  164. void
  165. close_fd_bitmap (fdbp)
  166.      struct fd_bitmap *fdbp;
  167. {
  168.   register int i;
  169.  
  170.   if (fdbp)
  171.     {
  172.       for (i = 0; i < fdbp->size; i++)
  173.     if (fdbp->bitmap[i])
  174.       {
  175.         close (i);
  176.         fdbp->bitmap[i] = 0;
  177.       }
  178.     }
  179. }
  180.  
  181. /* Execute the command passed in COMMAND.  COMMAND is exactly what
  182.    read_command () places into GLOBAL_COMMAND.  See "command.h" for the
  183.    details of the command structure.
  184.  
  185.    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
  186.    return values.  Executing a command with nothing in it returns
  187.    EXECUTION_SUCCESS. */
  188. execute_command (command)
  189.      COMMAND *command;
  190. {
  191.   struct fd_bitmap *bitmap;
  192.   int result;
  193.  
  194.   current_fds_to_close = (struct fd_bitmap *)NULL;
  195.   bitmap = new_fd_bitmap (FD_BITMAP_DEFAULT_SIZE);
  196.   begin_unwind_frame ("execute-command");
  197.   add_unwind_protect (dispose_fd_bitmap, (char *)bitmap);
  198.  
  199.   /* Just do the command, but not asynchronously. */
  200.   result = execute_command_internal (command, 0, NO_PIPE, NO_PIPE, bitmap);
  201.  
  202.   dispose_fd_bitmap (bitmap);
  203.   discard_unwind_frame ("execute-command");
  204.  
  205. #if defined (PROCESS_SUBSTITUTION)
  206.   unlink_fifo_list ();
  207. #endif /* PROCESS_SUBSTITUTION */
  208.  
  209.   return (result);
  210. }
  211.  
  212. /* Return 1 if TYPE is a shell control structure type. */
  213. static int
  214. shell_control_structure (type)
  215.      enum command_type type;
  216. {
  217.   switch (type)
  218.     {
  219.     case cm_for:
  220. #if defined (SELECT_COMMAND)
  221.     case cm_select:
  222. #endif
  223.     case cm_case:
  224.     case cm_while:
  225.     case cm_until:
  226.     case cm_if:
  227.     case cm_group:
  228.       return (1);
  229.  
  230.     default:
  231.       return (0);
  232.     }
  233. }
  234.  
  235. /* A function to use to unwind_protect the redirection undo list
  236.    for loops. */
  237. static void
  238. cleanup_redirects (list)
  239.      REDIRECT *list;
  240. {
  241.   do_redirections (list, 1, 0, 0);
  242.   dispose_redirects (list);
  243. }
  244.  
  245. /* Function to unwind_protect the redirections for functions and builtins. */
  246. static void
  247. cleanup_func_redirects (list)
  248.      REDIRECT *list;
  249. {
  250.   do_redirections (list, 1, 0, 0);
  251. }
  252.  
  253. static void
  254. dispose_exec_redirects ()
  255. {
  256.   if (exec_redirection_undo_list)
  257.     {
  258.       dispose_redirects (exec_redirection_undo_list);
  259.       exec_redirection_undo_list = (REDIRECT *)NULL;
  260.     }
  261. }
  262.  
  263. #if defined (JOB_CONTROL)
  264. /* A function to restore the signal mask to its proper value when the shell
  265.    is interrupted or errors occur while creating a pipeline. */
  266. static int
  267. restore_signal_mask (set)
  268.      sigset_t set;
  269. {
  270.   return (sigprocmask (SIG_SETMASK, &set, (sigset_t *)NULL));
  271. }
  272. #endif /* JOB_CONTROL */
  273.  
  274. /* A debugging function that can be called from gdb, for instance. */
  275. void
  276. open_files ()
  277. {
  278.   register int i;
  279.   int f, fd_table_size;
  280.  
  281.   fd_table_size = getdtablesize ();
  282.  
  283.   fprintf (stderr, "pid %d open files:", getpid ());
  284.   for (i = 3; i < fd_table_size; i++)
  285.     {
  286.       if ((f = fcntl (i, F_GETFD, 0)) != -1)
  287.     fprintf (stderr, " %d (%s)", i, f ? "close" : "open");
  288.     }
  289.   fprintf (stderr, "\n");
  290. }
  291.  
  292. #define DESCRIBE_PID(pid) if (interactive) describe_pid (pid)
  293.  
  294. /* Execute the command passed in COMMAND, perhaps doing it asynchrounously.
  295.    COMMAND is exactly what read_command () places into GLOBAL_COMMAND.
  296.    ASYNCHROUNOUS, if non-zero, says to do this command in the background.
  297.    PIPE_IN and PIPE_OUT are file descriptors saying where input comes
  298.    from and where it goes.  They can have the value of NO_PIPE, which means
  299.    I/O is stdin/stdout.
  300.    FDS_TO_CLOSE is a list of file descriptors to close once the child has
  301.    been forked.  This list often contains the unusable sides of pipes, etc.
  302.  
  303.    EXECUTION_SUCCESS or EXECUTION_FAILURE are the only possible
  304.    return values.  Executing a command with nothing in it returns
  305.    EXECUTION_SUCCESS. */
  306. execute_command_internal (command, asynchronous, pipe_in, pipe_out, 
  307.               fds_to_close)
  308.      COMMAND *command;
  309.      int asynchronous;
  310.      int pipe_in, pipe_out;
  311.      struct fd_bitmap *fds_to_close;
  312. {
  313.   int exec_result = EXECUTION_SUCCESS;
  314.   int invert, ignore_return;
  315.   REDIRECT *my_undo_list, *exec_undo_list;
  316.  
  317.   if (!command || breaking || continuing)
  318.     return (EXECUTION_SUCCESS);
  319.  
  320.   run_pending_traps ();
  321.  
  322.   invert = (command->flags & CMD_INVERT_RETURN) != 0;
  323.  
  324.   /* If a command was being explicitly run in a subshell, or if it is
  325.      a shell control-structure, and it has a pipe, then we do the command
  326.      in a subshell. */
  327.  
  328.   if ((command->flags & CMD_WANT_SUBSHELL) ||
  329.       (command->flags & CMD_FORCE_SUBSHELL)  ||
  330.       (shell_control_structure (command->type) &&
  331.        (pipe_out != NO_PIPE || pipe_in != NO_PIPE || asynchronous)))
  332.     {
  333.       pid_t paren_pid;
  334.  
  335.       /* Fork a subshell, turn off the subshell bit, turn off job
  336.      control and call execute_command () on the command again. */
  337.       paren_pid = make_child (savestring (make_command_string (command)),
  338.                   asynchronous);
  339.       if (paren_pid == 0)
  340.     {
  341.       int user_subshell, return_code, function_value;
  342.  
  343.       /* Cancel traps, in trap.c. */
  344.       restore_original_signals ();
  345.       if (asynchronous)
  346.         setup_async_signals ();
  347.  
  348. #if defined (JOB_CONTROL)
  349.       set_sigchld_handler ();
  350. #endif /* JOB_CONTROL */
  351.  
  352.       set_sigint_handler ();
  353.  
  354.       user_subshell = (command->flags & CMD_WANT_SUBSHELL) != 0;
  355.       command->flags &= ~(CMD_FORCE_SUBSHELL | CMD_WANT_SUBSHELL | CMD_INVERT_RETURN);
  356.  
  357.       /* If a command is asynchronous in a subshell (like ( foo ) & or
  358.          the special case of an asynchronous GROUP command where the
  359.          the subshell bit is turned on down in case cm_group: below), 
  360.          turn off `asynchronous', so that two subshells aren't spawned.
  361.  
  362.          This seems semantically correct to me.  For example, 
  363.          ( foo ) & seems to say ``do the command `foo' in a subshell
  364.          environment, but don't wait for that subshell to finish'',
  365.          and "{ foo ; bar } &" seems to me to be like functions or
  366.          builtins in the background, which executed in a subshell
  367.          environment.  I just don't see the need to fork two subshells. */
  368.  
  369.       /* Don't fork again, we are already in a subshell.  A `doubly
  370.          async' shell is not interactive, however. */
  371.       if (asynchronous)
  372.         {
  373. #if defined (JOB_CONTROL)
  374.           /* If a construct like ( exec xxx yyy ) & is given while job
  375.          control is active, we want to prevent exec from putting the
  376.          subshell back into the original process group, carefully
  377.          undoing all the work we just did in make_child. */
  378.           original_pgrp = -1;
  379. #endif /* JOB_CONTROL */
  380.           interactive_shell = 0;
  381.           asynchronous = 0;
  382.         }
  383.  
  384.       /* Subshells are neither login nor interactive. */
  385.       login_shell = interactive = 0;
  386.  
  387.       subshell_environment = 1;
  388.  
  389. #if defined (JOB_CONTROL)
  390.       /* Delete all traces that there were any jobs running.  This is
  391.          only for subshells. */
  392.       without_job_control ();
  393. #endif /* JOB_CONTROL */
  394.       do_piping (pipe_in, pipe_out);
  395.  
  396.       /* If this is a user subshell, set a flag if stdin was redirected.
  397.          This is used later to decide whether to redirect fd 0 to
  398.          /dev/null for async commands in the subshell.  This adds more
  399.          sh compatibility, but I'm not sure it's the right thing to do. */
  400.       if (user_subshell)
  401.         {
  402.           REDIRECT *r;
  403.  
  404.           for (r = command->redirects; r; r = r->next)
  405.         switch (r->instruction)
  406.           {
  407.           case r_input_direction:
  408.           case r_inputa_direction:
  409.           case r_input_output:
  410.           case r_reading_until:
  411.           case r_deblank_reading_until:
  412.             stdin_redir++;
  413.             break;
  414.           case r_duplicating_input:
  415.           case r_duplicating_input_word:
  416.           case r_close_this:
  417.             if (r->redirector == 0)
  418.               stdin_redir++;
  419.             break;
  420.           }
  421.         }
  422.  
  423.       if (fds_to_close)
  424.         close_fd_bitmap (fds_to_close);
  425.  
  426.       /* Do redirections, then dispose of them before recursive call. */
  427.       if (command->redirects)
  428.         {
  429.           if (do_redirections (command->redirects, 1, 0, 0) != 0)
  430.         exit (EXECUTION_FAILURE);
  431.  
  432.           dispose_redirects (command->redirects);
  433.           command->redirects = (REDIRECT *)NULL;
  434.         }
  435.  
  436.       /* If this is a simple command, tell execute_disk_command that it
  437.          might be able to get away without forking and simply exec.
  438.          This means things like ( sleep 10 ) will only cause one fork. */
  439.       if (user_subshell && command->type == cm_simple)
  440.         {
  441.           command->flags |= CMD_NO_FORK;
  442.           command->value.Simple->flags |= CMD_NO_FORK;
  443.         }
  444.  
  445.       /* If we're inside a function while executing this subshell, we
  446.          need to handle a possible `return'. */
  447.       function_value = 0;
  448.       if (return_catch_flag)
  449.         function_value =  setjmp (return_catch);
  450.  
  451.       if (function_value)
  452.         return_code = return_catch_value;
  453.       else
  454.         return_code = execute_command_internal
  455.           (command, asynchronous, NO_PIPE, NO_PIPE, fds_to_close);
  456.  
  457.       /* If we were explicitly placed in a subshell with (), we need
  458.          to do the `shell cleanup' things, such as running traps[0]. */
  459.       if (user_subshell)
  460.         run_exit_trap ();
  461.  
  462.       exit (return_code);
  463.     }
  464.       else
  465.     {
  466.       close_pipes (pipe_in, pipe_out);
  467.  
  468. #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
  469.       unlink_fifo_list ();
  470. #endif
  471.       /* If we are part of a pipeline, and not the end of the pipeline,
  472.          then we should simply return and let the last command in the
  473.          pipe be waited for.  If we are not in a pipeline, or are the
  474.          last command in the pipeline, then we wait for the subshell 
  475.          and return its exit status as usual. */
  476.       if (pipe_out != NO_PIPE)
  477.         return (EXECUTION_SUCCESS);
  478.  
  479.       stop_pipeline (asynchronous, (COMMAND *)NULL);
  480.  
  481.       if (!asynchronous)
  482.         {
  483.           last_command_exit_value = wait_for (paren_pid);
  484.  
  485.           /* If we have to, invert the return value. */
  486.           if (invert)
  487.         {
  488.           if (last_command_exit_value == EXECUTION_SUCCESS)
  489.             return (EXECUTION_FAILURE);
  490.           else
  491.             return (EXECUTION_SUCCESS);
  492.         }
  493.           else
  494.         return (last_command_exit_value);
  495.         }
  496.       else
  497.         {
  498.           DESCRIBE_PID (paren_pid);
  499.  
  500.           run_pending_traps ();
  501.  
  502.           return (EXECUTION_SUCCESS);
  503.         }
  504.     }
  505.     }
  506.  
  507.   /* Handle WHILE FOR CASE etc. with redirections.  (Also '&' input
  508.      redirection.)  */
  509.   if (do_redirections (command->redirects, 1, 1, 0) != 0)
  510.     {
  511.       cleanup_redirects (redirection_undo_list);
  512.       redirection_undo_list = (REDIRECT *)NULL;
  513.       dispose_exec_redirects ();
  514.       return (EXECUTION_FAILURE);
  515.     }
  516.  
  517.   if (redirection_undo_list)
  518.     {
  519.       my_undo_list = (REDIRECT *)copy_redirects (redirection_undo_list);
  520.       dispose_redirects (redirection_undo_list);
  521.       redirection_undo_list = (REDIRECT *)NULL;
  522.     }
  523.   else
  524.     my_undo_list = (REDIRECT *)NULL;
  525.  
  526.   if (exec_redirection_undo_list)
  527.     {
  528.       exec_undo_list = (REDIRECT *)copy_redirects (exec_redirection_undo_list);
  529.       dispose_redirects (exec_redirection_undo_list);
  530.       exec_redirection_undo_list = (REDIRECT *)NULL;
  531.     }
  532.   else
  533.     exec_undo_list = (REDIRECT *)NULL;
  534.  
  535.   if (my_undo_list || exec_undo_list)
  536.     begin_unwind_frame ("loop_redirections");
  537.  
  538.   if (my_undo_list)
  539.     add_unwind_protect ((Function *)cleanup_redirects, my_undo_list);
  540.  
  541.   if (exec_undo_list)
  542.     add_unwind_protect ((Function *)dispose_redirects, exec_undo_list);
  543.  
  544.   ignore_return = (command->flags & CMD_IGNORE_RETURN) != 0;
  545.  
  546.   QUIT;
  547.  
  548.   switch (command->type)
  549.     {
  550.     case cm_for:
  551.       if (ignore_return)
  552.     command->value.For->flags |= CMD_IGNORE_RETURN;
  553.       exec_result = execute_for_command (command->value.For);
  554.       break;
  555.  
  556. #if defined (SELECT_COMMAND)
  557.     case cm_select:
  558.       if (ignore_return)
  559.     command->value.Select->flags |= CMD_IGNORE_RETURN;
  560.       exec_result = execute_select_command (command->value.Select);
  561.       break;
  562. #endif
  563.  
  564.     case cm_case:
  565.       if (ignore_return)
  566.     command->value.Case->flags |= CMD_IGNORE_RETURN;
  567.       exec_result = execute_case_command (command->value.Case);
  568.       break;
  569.  
  570.     case cm_while:
  571.       if (ignore_return)
  572.     command->value.While->flags |= CMD_IGNORE_RETURN;
  573.       exec_result = execute_while_command (command->value.While);
  574.       break;
  575.  
  576.     case cm_until:
  577.       if (ignore_return)
  578.     command->value.While->flags |= CMD_IGNORE_RETURN;
  579.       exec_result = execute_until_command (command->value.While);
  580.       break;
  581.  
  582.     case cm_if:
  583.       if (ignore_return)
  584.     command->value.If->flags |= CMD_IGNORE_RETURN;
  585.       exec_result = execute_if_command (command->value.If);
  586.       break;
  587.  
  588.     case cm_group:
  589.  
  590.       /* This code can be executed from either of two paths: an explicit
  591.      '{}' command, or via a function call.  If we are executed via a
  592.      function call, we have already taken care of the function being
  593.      executed in the background (down there in execute_simple_command ()),
  594.      and this command should *not* be marked as asynchronous.  If we
  595.      are executing a regular '{}' group command, and asynchronous == 1,
  596.      we must want to execute the whole command in the background, so we
  597.      need a subshell, and we want the stuff executed in that subshell
  598.      (this group command) to be executed in the foreground of that
  599.      subshell (i.e. there will not be *another* subshell forked).
  600.  
  601.      What we do is to force a subshell if asynchronous, and then call
  602.      execute_command_internal again with asynchronous still set to 1,
  603.      but with the original group command, so the printed command will
  604.      look right.
  605.  
  606.      The code above that handles forking off subshells will note that
  607.      both subshell and async are on, and turn off async in the child
  608.      after forking the subshell (but leave async set in the parent, so
  609.      the normal call to describe_pid is made).  This turning off
  610.      async is *crucial*; if it is not done, this will fall into an
  611.      infinite loop of executions through this spot in subshell after
  612.      subshell until the process limit is exhausted. */
  613.  
  614.       if (asynchronous)
  615.     {
  616.       command->flags |= CMD_FORCE_SUBSHELL;
  617.       exec_result =
  618.         execute_command_internal (command, 1, pipe_in, pipe_out,
  619.                       fds_to_close);
  620.     }
  621.       else
  622.     {
  623.       if (ignore_return && command->value.Group->command)
  624.         command->value.Group->command->flags |= CMD_IGNORE_RETURN;
  625.       exec_result =
  626.         execute_command_internal (command->value.Group->command,
  627.                       asynchronous, pipe_in, pipe_out,
  628.                       fds_to_close);
  629.     }
  630.       break;
  631.  
  632.     case cm_simple:
  633.       {
  634.     /* We can't rely on this variable retaining its value across a
  635.        call to execute_simple_command if a longjmp occurs as the
  636.        result of a `return' builtin.  This is true for sure with gcc. */
  637.     pid_t last_pid = last_made_pid;
  638.  
  639.     if (ignore_return && command->value.Simple)
  640.       command->value.Simple->flags |= CMD_IGNORE_RETURN;
  641.     exec_result =
  642.       execute_simple_command (command->value.Simple, pipe_in, pipe_out,
  643.                   asynchronous, fds_to_close);
  644.  
  645.     /* The temporary environment should be used for only the simple
  646.        command immediately following its definition. */
  647.     dispose_used_env_vars ();
  648.  
  649. #if (defined (Ultrix) && defined (mips)) || !defined (HAVE_ALLOCA)
  650.     /* Reclaim memory allocated with alloca () on machines which
  651.        may be using the alloca emulation code. */
  652.     (void) alloca (0);
  653. #endif /* (Ultrix && mips) || !HAVE_ALLOCA */
  654.  
  655.     /* If we forked to do the command, then we must wait_for ()
  656.        the child. */
  657.  
  658.     /* XXX - this is something to watch out for if there are problems
  659.        when the shell is compiled without job control. */
  660.     if (already_making_children && pipe_out == NO_PIPE &&
  661.         last_pid != last_made_pid)
  662.       {
  663.         stop_pipeline (asynchronous, (COMMAND *)NULL);
  664.  
  665.         if (asynchronous)
  666.           {
  667.         DESCRIBE_PID (last_made_pid);
  668.           }
  669.         else
  670. #if !defined (JOB_CONTROL)
  671.           /* Do not wait for asynchronous processes started from
  672.          startup files. */
  673.         if (last_made_pid != last_asynchronous_pid)
  674. #endif
  675.         /* When executing a shell function that executes other
  676.            commands, this causes the last simple command in
  677.            the function to be waited for twice. */
  678.           exec_result = wait_for (last_made_pid);
  679.       }
  680.       }
  681.  
  682.       if (!ignore_return && exit_immediately_on_error && !invert &&
  683.       (exec_result != EXECUTION_SUCCESS))
  684.     {
  685.       last_command_exit_value = exec_result;
  686.       run_pending_traps ();
  687.       longjmp (top_level, EXITPROG);
  688.     }
  689.  
  690.       break;
  691.  
  692.     case cm_connection:
  693.       switch (command->value.Connection->connector)
  694.     {
  695.       /* Do the first command asynchronously. */
  696.     case '&':
  697.       {
  698.         COMMAND *tc = command->value.Connection->first;
  699.         REDIRECT *rp;
  700.  
  701.         if (!tc)
  702.           break;
  703.  
  704.         rp = tc->redirects;
  705.  
  706.         if (ignore_return && tc)
  707.           tc->flags |= CMD_IGNORE_RETURN;
  708.  
  709.         /* If this shell was compiled without job control support, if
  710.            the shell is not running interactively, if we are currently
  711.            in a subshell via `( xxx )', or if job control is not active
  712.            then the standard input for an asynchronous command is
  713.            forced to /dev/null. */
  714. #if defined (JOB_CONTROL)
  715.         if ((!interactive_shell || subshell_environment || !job_control) &&
  716.         !stdin_redir)
  717. #else
  718.         if (!stdin_redir)
  719. #endif /* JOB_CONTROL */
  720.         {
  721.           REDIRECT *tr;
  722.  
  723.           rd.filename = make_word ("/dev/null");
  724.           tr = make_redirection (0, r_inputa_direction, rd);
  725.           tr->next = tc->redirects;
  726.           tc->redirects = tr;
  727.         }
  728.  
  729.         exec_result = execute_command_internal
  730.           (tc, 1, pipe_in, pipe_out, fds_to_close);
  731.  
  732. #if defined (JOB_CONTROL)
  733.         if ((!interactive_shell || subshell_environment || !job_control) &&
  734.         !stdin_redir)
  735. #else
  736.         if (!stdin_redir)
  737. #endif /* JOB_CONTROL */
  738.         {
  739.           /* Remove the redirection we added above.  It matters,
  740.          especially for loops, which call execute_command ()
  741.          multiple times with the same command. */
  742.           REDIRECT *tr, *tl;
  743.  
  744.           tr = tc->redirects;
  745.           do
  746.         {
  747.           tl = tc->redirects;
  748.           tc->redirects = tc->redirects->next;
  749.         }
  750.           while (tc->redirects && tc->redirects != rp);
  751.  
  752.           tl->next = (REDIRECT *)NULL;
  753.           dispose_redirects (tr);
  754.         }
  755.  
  756.         {
  757.           register COMMAND *second;
  758.  
  759.           second = command->value.Connection->second;
  760.  
  761.           if (second)
  762.         {
  763.           if (ignore_return)
  764.             second->flags |= CMD_IGNORE_RETURN;
  765.  
  766.           exec_result = execute_command_internal
  767.             (second, asynchronous, pipe_in, pipe_out, fds_to_close);
  768.         }
  769.         }
  770.       }
  771.       break;
  772.  
  773.     case ';':
  774.       /* Just call execute command on both of them. */
  775.       if (ignore_return)
  776.         {
  777.           if (command->value.Connection->first)
  778.         command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
  779.           if (command->value.Connection->second)
  780.         command->value.Connection->second->flags |= CMD_IGNORE_RETURN;
  781.         }
  782.       QUIT;
  783.       execute_command (command->value.Connection->first);
  784.       QUIT;
  785.       exec_result =
  786.         execute_command_internal (command->value.Connection->second,
  787.                       asynchronous, pipe_in, pipe_out,
  788.                       fds_to_close);
  789.       break;
  790.  
  791.     case '|':
  792.       {
  793.         int prev, fildes[2], new_bitmap_size, dummyfd;
  794.         COMMAND *cmd;
  795.         struct fd_bitmap *fd_bitmap;
  796.  
  797. #if defined (JOB_CONTROL)
  798.         sigset_t set, oset;
  799.         BLOCK_CHILD (set, oset);
  800. #endif /* JOB_CONTROL */
  801.  
  802.         prev = pipe_in;
  803.         cmd = command;
  804.  
  805.         while (cmd &&
  806.            cmd->type == cm_connection &&
  807.            cmd->value.Connection &&
  808.            cmd->value.Connection->connector == '|')
  809.           {
  810.         /* Make a pipeline between the two commands. */
  811.         if (pipe (fildes) < 0)
  812.           {
  813.             report_error ("pipe error: %s", strerror (errno));
  814. #if defined (JOB_CONTROL)
  815.             terminate_current_pipeline ();
  816.             kill_current_pipeline ();
  817. #endif /* JOB_CONTROL */
  818.             last_command_exit_value = EXECUTION_FAILURE;
  819.             /* The unwind-protects installed below will take care
  820.                of closing all of the open file descriptors. */
  821.             throw_to_top_level ();
  822.           }
  823.         else
  824.           {
  825.             /* Here is a problem: with the new file close-on-exec
  826.                code, the read end of the pipe (fildes[0]) stays open
  827.                in the first process, so that process will never get a
  828.                SIGPIPE.  There is no way to signal the first process
  829.                that it should close fildes[0] after forking, so it
  830.                remains open.  No SIGPIPE is ever sent because there
  831.                is still a file descriptor open for reading connected
  832.                to the pipe.  We take care of that here.  This passes
  833.                around a bitmap of file descriptors that must be
  834.                closed after making a child process in
  835.                execute_simple_command. */
  836.  
  837.             /* We need fd_bitmap to be at least as big as fildes[0].
  838.                If fildes[0] is less than fds_to_close->size, then
  839.                use fds_to_close->size. */
  840.             if (fildes[0] < fds_to_close->size)
  841.               new_bitmap_size = fds_to_close->size;
  842.             else
  843.               new_bitmap_size = fildes[0] + 8;
  844.  
  845.             fd_bitmap = new_fd_bitmap (new_bitmap_size);
  846.  
  847.             /* Now copy the old information into the new bitmap. */
  848.             xbcopy ((char *)fds_to_close->bitmap,
  849.                 (char *)fd_bitmap->bitmap, fds_to_close->size);
  850.  
  851.             /* And mark the pipe file descriptors to be closed. */
  852.             fd_bitmap->bitmap[fildes[0]] = 1;
  853.  
  854.             /* In case there are pipe or out-of-processes errors, we
  855.                want all these file descriptors to be closed when
  856.                unwind-protects are run, and the storage used for the
  857.                bitmaps freed up. */
  858.             begin_unwind_frame ("pipe-file-descriptors");
  859.             add_unwind_protect (dispose_fd_bitmap, fd_bitmap);
  860.             add_unwind_protect (close_fd_bitmap, fd_bitmap);
  861.             if (prev >= 0)
  862.               add_unwind_protect (close, prev);
  863.             dummyfd = fildes[1];
  864.             add_unwind_protect (close, dummyfd);
  865.  
  866. #if defined (JOB_CONTROL)
  867.             add_unwind_protect (restore_signal_mask, oset);
  868. #endif /* JOB_CONTROL */
  869.  
  870.             if (ignore_return && cmd->value.Connection->first)
  871.               cmd->value.Connection->first->flags |=
  872.             CMD_IGNORE_RETURN;
  873.             execute_command_internal
  874.               (cmd->value.Connection->first, asynchronous, prev,
  875.                fildes[1], fd_bitmap);
  876.  
  877.             if (prev >= 0)
  878.               close (prev);
  879.             
  880.             prev = fildes[0];
  881.             close (fildes[1]);
  882.  
  883.             dispose_fd_bitmap (fd_bitmap);
  884.             discard_unwind_frame ("pipe-file-descriptors");
  885.           }
  886.         cmd = cmd->value.Connection->second;
  887.           }
  888.  
  889.         /* Now execute the rightmost command in the pipeline.  */
  890.         if (ignore_return && cmd)
  891.           cmd->flags |= CMD_IGNORE_RETURN;
  892.         exec_result =
  893.           execute_command_internal
  894.         (cmd, asynchronous, prev, pipe_out, fds_to_close);
  895.  
  896.         if (prev >= 0)
  897.           close (prev);
  898.  
  899. #if defined (JOB_CONTROL)
  900.         UNBLOCK_CHILD (oset);
  901. #endif
  902.       }
  903.       break;
  904.  
  905.     case AND_AND:
  906.     case OR_OR:
  907.       if (asynchronous)
  908.         {
  909.           /* If we have something like `a && b &' or `a || b &', run the
  910.              && or || stuff in a subshell.  Force a subshell and just call
  911.          execute_command_internal again.  Leave asynchronous on
  912.          so that we get a report from the parent shell about the
  913.          background job. */
  914.           command->flags |= CMD_FORCE_SUBSHELL;
  915.           exec_result = execute_command_internal (command, 1, pipe_in,
  916.                   pipe_out, fds_to_close);
  917.           break;
  918.         }
  919.  
  920.       /* Execute the first command.  If the result of that is successful
  921.          and the connector is AND_AND, or the result is not successful
  922.          and the connector is OR_OR, then execute the second command,
  923.          otherwise return. */
  924.  
  925.       if (command->value.Connection->first)
  926.         command->value.Connection->first->flags |= CMD_IGNORE_RETURN;
  927.  
  928.       exec_result = execute_command (command->value.Connection->first);
  929.       QUIT;
  930.       if (((command->value.Connection->connector == AND_AND) && 
  931.            (exec_result == EXECUTION_SUCCESS)) ||
  932.           ((command->value.Connection->connector == OR_OR) &&
  933.            (exec_result != EXECUTION_SUCCESS)))
  934.         {
  935.           if (ignore_return && command->value.Connection->second)
  936.         command->value.Connection->second->flags |=
  937.           CMD_IGNORE_RETURN;
  938.  
  939.           exec_result =
  940.         execute_command (command->value.Connection->second);
  941.         }
  942.       break;
  943.  
  944.     default:
  945.       programming_error ("Bad connector `%d'!",
  946.                  command->value.Connection->connector);
  947.       longjmp (top_level, DISCARD);
  948.       break;
  949.     }
  950.       break;
  951.  
  952.     case cm_function_def:
  953.       exec_result = intern_function (command->value.Function_def->name,
  954.                      command->value.Function_def->command);
  955.       break;
  956.  
  957.     default:
  958.       programming_error
  959.     ("execute_command: Bad command type `%d'!", command->type);
  960.     }
  961.  
  962.   if (my_undo_list)
  963.     {
  964.       do_redirections (my_undo_list, 1, 0, 0);
  965.       dispose_redirects (my_undo_list);
  966.     }
  967.  
  968.   if (exec_undo_list)
  969.     dispose_redirects (exec_undo_list);
  970.  
  971.   if (my_undo_list || exec_undo_list)
  972.     discard_unwind_frame ("loop_redirections");
  973.  
  974.   /* Invert the return value if we have to */
  975.   if (invert)
  976.     {
  977.       if (exec_result == EXECUTION_SUCCESS)
  978.     exec_result = EXECUTION_FAILURE;
  979.       else
  980.     exec_result = EXECUTION_SUCCESS;
  981.     }
  982.  
  983.   last_command_exit_value = exec_result;
  984.   run_pending_traps ();
  985.   return (last_command_exit_value);
  986. }
  987.  
  988. #if defined (JOB_CONTROL)
  989. #  define REAP() \
  990.     do \
  991.       { \
  992.         if (!interactive_shell) \
  993.           reap_dead_jobs (); \
  994.       } \
  995.     while (0)
  996. #else /* !JOB_CONTROL */
  997. #  define REAP() \
  998.     do \
  999.       { \
  1000.         if (!interactive_shell) \
  1001.           cleanup_dead_jobs (); \
  1002.       } \
  1003.     while (0)
  1004. #endif /* !JOB_CONTROL */
  1005.  
  1006.  
  1007. /* Execute a FOR command.  The syntax is: FOR word_desc IN word_list;
  1008.    DO command; DONE */
  1009. execute_for_command (for_command)
  1010.      FOR_COM *for_command;
  1011. {
  1012.   /* I just noticed that the Bourne shell leaves word_desc bound to the
  1013.      last name in word_list after the FOR statement is done.  This seems
  1014.      wrong to me; I thought that the variable binding should be lexically
  1015.      scoped, i.e., only would last the duration of the FOR command.  This
  1016.      behaviour can be gotten by turning on the lexical_scoping switch. */
  1017.  
  1018.   register WORD_LIST *releaser, *list;
  1019.   char *identifier;
  1020.   SHELL_VAR *old_value = (SHELL_VAR *)NULL; /* Remember the old value of x. */
  1021.   int retval = EXECUTION_SUCCESS;
  1022.  
  1023.   if (check_identifier (for_command->name, 1) == 0)
  1024.     return (EXECUTION_FAILURE);
  1025.  
  1026.   loop_level++;
  1027.   identifier = for_command->name->word;
  1028.  
  1029.   list = releaser = expand_words (for_command->map_list);
  1030.  
  1031.   begin_unwind_frame ("for");
  1032.   add_unwind_protect (dispose_words, releaser);
  1033.  
  1034.   if (lexical_scoping)
  1035.     {
  1036.       old_value = copy_variable (find_variable (identifier));
  1037.       if (old_value)
  1038.     add_unwind_protect (dispose_variable, old_value);
  1039.     }
  1040.  
  1041.   if (for_command->flags & CMD_IGNORE_RETURN)
  1042.     for_command->action->flags |= CMD_IGNORE_RETURN;
  1043.  
  1044.   while (list)
  1045.     {
  1046.       QUIT;
  1047.       bind_variable (identifier, list->word->word);
  1048.       execute_command (for_command->action);
  1049.       retval = last_command_exit_value;
  1050.       REAP ();
  1051.       QUIT;
  1052.  
  1053.       if (breaking)
  1054.     {
  1055.       breaking--; 
  1056.       break;
  1057.     }
  1058.  
  1059.       if (continuing)
  1060.     {
  1061.       continuing--;
  1062.       if (continuing)
  1063.         break;
  1064.     }
  1065.  
  1066.       list = list->next;
  1067.     }
  1068.  
  1069.   loop_level--;
  1070.  
  1071.   if (lexical_scoping)
  1072.     {
  1073.       if (!old_value)
  1074.     makunbound (identifier, shell_variables);
  1075.       else
  1076.     {
  1077.       SHELL_VAR *new_value;
  1078.  
  1079.       new_value = bind_variable (identifier, value_cell(old_value));
  1080.       new_value->attributes = old_value->attributes;
  1081.       dispose_variable (old_value);
  1082.     }
  1083.     }
  1084.  
  1085.   dispose_words (releaser);
  1086.   discard_unwind_frame ("for");
  1087.   return (retval);
  1088. }
  1089.  
  1090. #if defined (SELECT_COMMAND)
  1091. static int LINES, COLS, tabsize;
  1092.  
  1093. #define RP_SPACE ") "
  1094. #define RP_SPACE_LEN 2
  1095.  
  1096. /* XXX - does not handle numbers > 1000000 at all. */
  1097. #define NUMBER_LEN(s) \
  1098. ((s < 10) ? 1 \
  1099.       : ((s < 100) ? 2 \
  1100.               : ((s < 1000) ? 3 \
  1101.                    : ((s < 10000) ? 4 \
  1102.                          : ((s < 100000) ? 5 \
  1103.                                 : 6)))))
  1104.  
  1105. static int
  1106. print_index_and_element (len, ind, list)
  1107.       int len, ind;
  1108.       WORD_LIST *list;
  1109. {
  1110.   register WORD_LIST *l;
  1111.   register int i;
  1112.  
  1113.   i = ind;
  1114.   l = list;
  1115.   while (l && --i)
  1116.     l = l->next;
  1117.   fprintf (stderr, "%*d%s%s", len, ind, RP_SPACE, l->word->word);
  1118.   return (STRLEN (l->word->word));
  1119. }
  1120.  
  1121. static void
  1122. indent (from, to)
  1123.      int from, to;
  1124. {
  1125.   while (from < to)
  1126.     {
  1127.       if ((to / tabsize) > (from / tabsize))
  1128.     {
  1129.       putc ('\t', stderr);
  1130.       from += tabsize - from % tabsize;
  1131.     }
  1132.       else
  1133.     {
  1134.       putc (' ', stderr);
  1135.       from++;
  1136.     }
  1137.     }
  1138. }
  1139.  
  1140. static void
  1141. print_select_list (list, list_len, max_elem_len, indices_len)
  1142.      WORD_LIST *list;
  1143.      int list_len, max_elem_len, indices_len;
  1144. {
  1145.   int ind, row, elem_len, pos, cols, rows;
  1146.   int first_column_indices_len, other_indices_len;
  1147.  
  1148.   cols = COLS / max_elem_len;
  1149.   if (cols == 0)
  1150.     cols = 1;
  1151.   rows = list_len / cols + (list_len % cols != 0);
  1152.   cols = list_len / rows + (list_len % rows != 0);
  1153.  
  1154.   if (rows == 1)
  1155.     {
  1156.       rows = cols;
  1157.       cols = 1;
  1158.     }
  1159.  
  1160.   first_column_indices_len = NUMBER_LEN (rows);
  1161.   other_indices_len = indices_len;
  1162.  
  1163.   for (row = 0; row < rows; row++)
  1164.     {
  1165.       ind = row;
  1166.       pos = 0;
  1167.       while (1)
  1168.     {
  1169.       indices_len = (pos == 0) ? first_column_indices_len : other_indices_len;
  1170.       elem_len = print_index_and_element (indices_len, ind + 1, list);
  1171.       elem_len += indices_len + RP_SPACE_LEN;
  1172.       ind += rows;
  1173.       if (ind >= list_len)
  1174.         break;
  1175.       indent (pos + elem_len, pos + max_elem_len);
  1176.       pos += max_elem_len;
  1177.     }
  1178.       putc ('\n', stderr);
  1179.     }
  1180. }
  1181.  
  1182. /* Print the elements of LIST, one per line, preceded by an index from 1 to
  1183.    LIST_LEN.  Then display PROMPT and wait for the user to enter a number.
  1184.    If the number is between 1 and LIST_LEN, return that selection.  If EOF
  1185.    is read, return a null string.  If a blank line is entered, the loop is
  1186.    executed again. */
  1187. static char *
  1188. select_query (list, list_len, prompt)
  1189.      WORD_LIST *list;
  1190.      int list_len;
  1191.      char *prompt;
  1192. {
  1193.   int max_elem_len, indices_len, len, reply;
  1194.   WORD_LIST *l;
  1195.   char *repl_string, *t;
  1196.  
  1197.   t = get_string_value ("LINES");
  1198.   LINES = (t && *t) ? atoi (t) : 24;
  1199.   t = get_string_value ("COLUMNS");
  1200.   COLS =  (t && *t) ? atoi (t) : 80;
  1201.  
  1202. #if 0
  1203.   t = get_string_value ("TABSIZE");
  1204.   tabsize = (t && *t) ? atoi (t) : 8;
  1205.   if (tabsize <= 0)
  1206.     tabsize = 8;
  1207. #else
  1208.   tabsize = 8;
  1209. #endif
  1210.  
  1211.   max_elem_len = 0;
  1212.   for (l = list; l; l = l->next)
  1213.     {
  1214.       len = STRLEN (l->word->word);
  1215.       if (len > max_elem_len)
  1216.         max_elem_len = len;
  1217.     }
  1218.   indices_len = NUMBER_LEN (list_len);
  1219.   max_elem_len += indices_len + RP_SPACE_LEN + 2;
  1220.  
  1221.   while (1)
  1222.     {
  1223.       print_select_list (list, list_len, max_elem_len, indices_len);
  1224.       printf ("%s", prompt);
  1225.       fflush (stdout);
  1226.       QUIT;
  1227.  
  1228.       if (read_builtin ((WORD_LIST *)NULL) == EXECUTION_FAILURE)
  1229.     {
  1230.       putchar ('\n');
  1231.       return ((char *)NULL);
  1232.     }
  1233.       repl_string = get_string_value ("REPLY");
  1234.       if (*repl_string == 0)
  1235.     continue;
  1236.       reply = atoi (repl_string);
  1237.       if (reply < 1 || reply > list_len)
  1238.     return "";
  1239.  
  1240.       l = list;
  1241.       while (l && --reply)
  1242.         l = l->next;
  1243.       return (l->word->word);
  1244.     }
  1245. }
  1246.  
  1247. /* Execute a SELECT command.  The syntax is:
  1248.    SELECT word IN list DO command_list DONE
  1249.    Only `break' or `return' in command_list will terminate
  1250.    the command. */
  1251. execute_select_command (select_command)
  1252.      SELECT_COM *select_command;
  1253. {
  1254.   WORD_LIST *releaser, *list;
  1255.   char *identifier, *ps3_prompt, *selection;
  1256.   int retval, list_len, return_val;
  1257. #if 0
  1258.   SHELL_VAR *old_value = (SHELL_VAR *)0;
  1259. #endif
  1260.  
  1261.  
  1262.   retval = EXECUTION_SUCCESS;
  1263.  
  1264.   if (check_identifier (select_command->name, 1) == 0)
  1265.     return (EXECUTION_FAILURE);
  1266.  
  1267.   loop_level++;
  1268.   identifier = select_command->name->word;
  1269.  
  1270.   /* command and arithmetic substitution, parameter and variable expansion,
  1271.      word splitting, pathname expansion, and quote removal. */
  1272.   list = releaser = expand_words (select_command->map_list);
  1273.  
  1274.   begin_unwind_frame ("select");
  1275.   add_unwind_protect (dispose_words, releaser);
  1276.  
  1277. #if 0
  1278.   if (lexical_scoping)
  1279.     {
  1280.       old_value = copy_variable (find_variable (identifier));
  1281.       if (old_value)
  1282.     add_unwind_protect (dispose_variable, old_value);
  1283.     }
  1284. #endif
  1285.  
  1286.   if (select_command->flags & CMD_IGNORE_RETURN)
  1287.     select_command->action->flags |= CMD_IGNORE_RETURN;
  1288.  
  1289.   list_len = list_length (list);
  1290.   ps3_prompt = get_string_value ("PS3");
  1291.   if (!ps3_prompt)
  1292.     ps3_prompt = "#? ";
  1293.  
  1294.   unwind_protect_int (return_catch_flag);
  1295.   unwind_protect_jmp_buf (return_catch);
  1296.   return_catch_flag++;
  1297.  
  1298.   while (1)
  1299.     {
  1300.       QUIT;
  1301.       selection = select_query (list, list_len, ps3_prompt);
  1302.       QUIT;
  1303.       if (selection == 0)
  1304.     break;
  1305.       else
  1306.     bind_variable (identifier, selection);
  1307.  
  1308.       return_val = setjmp (return_catch);
  1309.  
  1310.       if (return_val)
  1311.         {
  1312.       retval = return_catch_value;
  1313.       break;
  1314.         }
  1315.       else
  1316.         retval = execute_command (select_command->action);
  1317.  
  1318.       REAP ();
  1319.       QUIT;
  1320.  
  1321.       if (breaking)
  1322.     {
  1323.       breaking--;
  1324.       break;
  1325.     }
  1326.     }
  1327.  
  1328.   loop_level--;
  1329.  
  1330. #if 0
  1331.   if (lexical_scoping)
  1332.     {
  1333.       if (!old_value)
  1334.     makunbound (identifier, shell_variables);
  1335.       else
  1336.     {
  1337.       SHELL_VAR *new_value;
  1338.  
  1339.       new_value = bind_variable (identifier, value_cell(old_value));
  1340.       new_value->attributes = old_value->attributes;
  1341.       dispose_variable (old_value);
  1342.     }
  1343.     }
  1344. #endif
  1345.  
  1346.   run_unwind_frame ("select");
  1347.   return (retval);
  1348. }
  1349. #endif /* SELECT_COMMAND */
  1350.  
  1351. /* Execute a CASE command.  The syntax is: CASE word_desc IN pattern_list ESAC.
  1352.    The pattern_list is a linked list of pattern clauses; each clause contains
  1353.    some patterns to compare word_desc against, and an associated command to
  1354.    execute. */
  1355. execute_case_command (case_command)
  1356.      CASE_COM *case_command;
  1357. {
  1358.   register WORD_LIST *list;
  1359.   WORD_LIST *wlist;
  1360.   PATTERN_LIST *clauses;
  1361.   char *word;
  1362.   int retval;
  1363.  
  1364.   /* Posix.2 specifies that the WORD is tilde expanded. */
  1365.   if (member ('~', case_command->word->word))
  1366.     {
  1367.       word = tilde_expand (case_command->word->word);
  1368.       free (case_command->word->word);
  1369.       case_command->word->word = word;
  1370.     }
  1371.  
  1372.   wlist = expand_word_no_split (case_command->word, 0);
  1373.   clauses = case_command->clauses;
  1374.   word = (wlist) ? string_list (wlist) : savestring ("");
  1375.   retval = EXECUTION_SUCCESS;
  1376.  
  1377.   begin_unwind_frame ("case");
  1378.   add_unwind_protect (dispose_words, wlist);
  1379.   add_unwind_protect ((Function *)xfree, word);
  1380.  
  1381.   while (clauses)
  1382.     {
  1383.       QUIT;
  1384.       list = clauses->patterns;
  1385.       while (list)
  1386.     {
  1387.       char *pattern;
  1388.       WORD_LIST *es;
  1389.       int match;
  1390.  
  1391.       /* Posix.2 specifies to tilde expand each member of the pattern
  1392.          list. */
  1393.       if (member ('~', list->word->word))
  1394.         {
  1395.           char *expansion = tilde_expand (list->word->word);
  1396.           free (list->word->word);
  1397.           list->word->word = expansion;
  1398.         }
  1399.  
  1400.       es = expand_word_leave_quoted (list->word, 0);
  1401.  
  1402.       if (es && es->word && es->word->word && *(es->word->word))
  1403.         pattern = quote_string_for_globbing (es->word->word, 1);
  1404.       else
  1405.         pattern = savestring ("");
  1406.  
  1407.       /* Since the pattern does not undergo quote removal (as per
  1408.          Posix.2, section 3.9.4.3), the fnmatch () call must be able
  1409.          to recognize backslashes as escape characters. */
  1410.       match = (fnmatch (pattern, word, 0) != FNM_NOMATCH);
  1411.       free (pattern);
  1412.  
  1413.       dispose_words (es);
  1414.  
  1415.       if (match)
  1416.         {
  1417.           if (clauses->action && 
  1418.           (case_command->flags & CMD_IGNORE_RETURN))
  1419.         clauses->action->flags |= CMD_IGNORE_RETURN;
  1420.           execute_command (clauses->action);
  1421.           retval = last_command_exit_value;
  1422.           goto exit_command;
  1423.         }
  1424.  
  1425.       list = list->next;
  1426.       QUIT;
  1427.     }
  1428.  
  1429.       clauses = clauses->next;
  1430.     }
  1431.  
  1432.  exit_command:
  1433.   dispose_words (wlist);
  1434.   free (word);  
  1435.   discard_unwind_frame ("case");
  1436.  
  1437.   return (retval);
  1438. }
  1439.  
  1440. #define CMD_WHILE 0
  1441. #define CMD_UNTIL 1
  1442.  
  1443. /* The WHILE command.  Syntax: WHILE test DO action; DONE.
  1444.    Repeatedly execute action while executing test produces
  1445.    EXECUTION_SUCCESS. */
  1446. execute_while_command (while_command)
  1447.      WHILE_COM *while_command;
  1448. {
  1449.   return (execute_while_or_until (while_command, CMD_WHILE));
  1450. }
  1451.  
  1452. /* UNTIL is just like WHILE except that the test result is negated. */
  1453. execute_until_command (while_command)
  1454.      WHILE_COM *while_command;
  1455. {
  1456.   return (execute_while_or_until (while_command, CMD_UNTIL));
  1457. }
  1458.  
  1459. /* The body for both while and until.  The only difference between the
  1460.    two is that the test value is treated differently.  TYPE is
  1461.    CMD_WHILE or CMD_UNTIL.  The return value for both commands should
  1462.    be EXECUTION_SUCCESS if no commands in the body are executed, and
  1463.    the status of the last command executed in the body otherwise. */
  1464. execute_while_or_until (while_command, type)
  1465.      WHILE_COM *while_command;
  1466.      int type;
  1467. {
  1468.   int return_value, body_status;
  1469.  
  1470.   body_status = EXECUTION_SUCCESS;
  1471.   loop_level++;
  1472.  
  1473.   while_command->test->flags |= CMD_IGNORE_RETURN;
  1474.   if (while_command->flags & CMD_IGNORE_RETURN)
  1475.     while_command->action->flags |= CMD_IGNORE_RETURN;
  1476.  
  1477.   while (1)
  1478.     {
  1479.       return_value = execute_command (while_command->test);
  1480.       REAP ();
  1481.  
  1482.       if (type == CMD_WHILE && return_value != EXECUTION_SUCCESS)
  1483.     break;
  1484.       if (type == CMD_UNTIL && return_value == EXECUTION_SUCCESS)
  1485.     break;
  1486.  
  1487.       QUIT;
  1488.       body_status = execute_command (while_command->action);
  1489.       QUIT;
  1490.  
  1491.       if (breaking)
  1492.     {
  1493.       breaking--;
  1494.       break;
  1495.     }
  1496.  
  1497.       if (continuing)
  1498.     {
  1499.       continuing--;
  1500.       if (continuing)
  1501.         break;
  1502.     }
  1503.     }
  1504.   loop_level--;
  1505.  
  1506.   return (body_status);
  1507. }
  1508.  
  1509. /* IF test THEN command [ELSE command].
  1510.    IF also allows ELIF in the place of ELSE IF, but
  1511.    the parser makes *that* stupidity transparent. */
  1512. execute_if_command (if_command)
  1513.      IF_COM *if_command;
  1514. {
  1515.   int return_value;
  1516.  
  1517.   if_command->test->flags |= CMD_IGNORE_RETURN;
  1518.   return_value = execute_command (if_command->test);
  1519.  
  1520.   if (return_value == EXECUTION_SUCCESS)
  1521.     {
  1522.       QUIT;
  1523.       if (if_command->true_case && (if_command->flags & CMD_IGNORE_RETURN))
  1524.       if_command->true_case->flags |= CMD_IGNORE_RETURN;
  1525.       return (execute_command (if_command->true_case));
  1526.     }
  1527.   else
  1528.     {
  1529.       QUIT;
  1530.  
  1531.       if (if_command->false_case && (if_command->flags & CMD_IGNORE_RETURN))
  1532.     if_command->false_case->flags |= CMD_IGNORE_RETURN;
  1533.  
  1534.       return (execute_command (if_command->false_case));
  1535.     }
  1536. }
  1537.  
  1538. static void
  1539. bind_lastarg (arg)
  1540.      char *arg;
  1541. {
  1542.   SHELL_VAR *var;
  1543.  
  1544.   if (!arg)
  1545.     arg = "";
  1546.   var = bind_variable ("_", arg);
  1547.   var->attributes &= ~att_exported;
  1548. }
  1549.  
  1550. /* The meaty part of all the executions.  We have to start hacking the
  1551.    real execution of commands here.  Fork a process, set things up,
  1552.    execute the command. */
  1553. execute_simple_command (simple_command, pipe_in, pipe_out, async, fds_to_close)
  1554.      SIMPLE_COM *simple_command;
  1555.      int pipe_in, pipe_out, async;
  1556.      struct fd_bitmap *fds_to_close;
  1557. {
  1558.   WORD_LIST *words, *lastword;
  1559.   char *command_line, *lastarg;
  1560.   int first_word_quoted, result;
  1561.   pid_t old_last_command_subst_pid;
  1562.  
  1563.   result = EXECUTION_SUCCESS;
  1564.  
  1565.   /* If we're in a function, update the pseudo-line-number information. */
  1566.   if (variable_context)
  1567.     line_number = simple_command->line - function_line_number;
  1568.  
  1569.   /* Remember what this command line looks like at invocation. */
  1570.   command_string_index = 0;
  1571.   print_simple_command (simple_command);
  1572.   command_line = (char *)alloca (1 + strlen (the_printed_command));
  1573.   strcpy (command_line, the_printed_command);
  1574.  
  1575.   first_word_quoted =
  1576.     simple_command->words ? simple_command->words->word->quoted : 0;
  1577.  
  1578.   old_last_command_subst_pid = last_command_subst_pid;
  1579.  
  1580.   /* If we are re-running this as the result of executing the `command'
  1581.      builtin, do not expand the command words a second time. */
  1582.   if ((simple_command->flags & CMD_INHIBIT_EXPANSION) == 0)
  1583.     {
  1584.       current_fds_to_close = fds_to_close;
  1585.       words = expand_words (simple_command->words);
  1586.       current_fds_to_close = (struct fd_bitmap *)NULL;
  1587.     }
  1588.   else
  1589.     words = copy_word_list (simple_command->words);
  1590.  
  1591.   lastarg = (char *)NULL;
  1592.  
  1593.   /* It is possible for WORDS not to have anything left in it.
  1594.      Perhaps all the words consisted of `$foo', and there was
  1595.      no variable `$foo'. */
  1596.   if (words)
  1597.     {
  1598.       Function *builtin;
  1599.       SHELL_VAR *func;
  1600.  
  1601.       begin_unwind_frame ("simple-command");
  1602.  
  1603.       if (echo_command_at_execute)
  1604.     {
  1605.       char *line = string_list (words);
  1606.  
  1607.       if (line && *line)
  1608.         fprintf (stderr, "%s%s\n", indirection_level_string (), line);
  1609.  
  1610.       FREE (line);
  1611.     }
  1612.  
  1613.       if (simple_command->flags & CMD_NO_FUNCTIONS)
  1614.     func = (SHELL_VAR *)NULL;
  1615.       else
  1616.     func = find_function (words->word->word);
  1617.  
  1618.       add_unwind_protect (dispose_words, words);
  1619.  
  1620.       QUIT;
  1621.  
  1622.       /* Bind the last word in this command to "$_" after execution. */
  1623.       for (lastword = words; lastword->next; lastword = lastword->next);
  1624.       lastarg = lastword->word->word;
  1625.  
  1626. #if defined (JOB_CONTROL)
  1627.       /* Is this command a job control related thing? */
  1628.       if (words->word->word[0] == '%')
  1629.     {
  1630.       int result;
  1631.  
  1632.       if (async)
  1633.         this_command_name = "bg";
  1634.       else
  1635.         this_command_name = "fg";
  1636.  
  1637.       last_shell_builtin = this_shell_builtin;
  1638.       this_shell_builtin = builtin_address (this_command_name);
  1639.       result = (*this_shell_builtin) (words);
  1640.       goto return_result;
  1641.     }
  1642.  
  1643.       /* One other possiblilty.  The user may want to resume an existing job.
  1644.      If they do, find out whether this word is a candidate for a running
  1645.      job. */
  1646.       {
  1647.     char *auto_resume_value = get_string_value ("auto_resume");
  1648.  
  1649.     if (auto_resume_value &&
  1650.         !first_word_quoted &&
  1651.         !words->next &&
  1652.         words->word->word[0] &&
  1653.         !simple_command->redirects &&
  1654.         pipe_in == NO_PIPE &&
  1655.         pipe_out == NO_PIPE &&
  1656.         !async)
  1657.       {
  1658.         char *word = words->word->word;
  1659.         register int i;
  1660.         int wl, cl, exact, substring, match, started_status;
  1661.         register PROCESS *p;
  1662.  
  1663.         exact = STREQ (auto_resume_value, "exact");
  1664.         substring = STREQ (auto_resume_value, "substring");
  1665.         wl = strlen (word);
  1666.         for (i = job_slots - 1; i > -1; i--)
  1667.           {
  1668.         if (!jobs[i] || (JOBSTATE (i) != JSTOPPED))
  1669.           continue;
  1670.  
  1671.         p = jobs[i]->pipe;
  1672.         do
  1673.           {
  1674.             if (exact)
  1675.               {
  1676.                 cl = strlen (p->command);
  1677.                 match = STREQN (p->command, word, cl);
  1678.               }
  1679.             else if (substring)
  1680.               match = strindex (p->command, word) != (char *)0;
  1681.             else
  1682.               match = STREQN (p->command, word, wl);
  1683.  
  1684.             if (match == 0)
  1685.               {
  1686.                 p = p->next;
  1687.                 continue;
  1688.               }
  1689.  
  1690.             run_unwind_frame ("simple-command");
  1691.             last_shell_builtin = this_shell_builtin;
  1692.             this_shell_builtin = builtin_address ("fg");
  1693.  
  1694.             started_status = start_job (i, 1);
  1695.  
  1696.             if (started_status < 0)
  1697.               return (EXECUTION_FAILURE);
  1698.             else
  1699.               return (started_status);
  1700.           }
  1701.         while (p != jobs[i]->pipe);
  1702.           }
  1703.       }
  1704.       }
  1705. #endif /* JOB_CONTROL */
  1706.  
  1707.       /* Remember the name of this command globally. */
  1708.       this_command_name = words->word->word;
  1709.  
  1710.       QUIT;
  1711.  
  1712.       /* This command could be a shell builtin or a user-defined function.
  1713.      If so, and we have pipes, then fork a subshell in here.  Else, just
  1714.      do the command. */
  1715.  
  1716.       if (func)
  1717.     builtin = (Function *)NULL;
  1718.       else
  1719.     builtin = find_shell_builtin (this_command_name);
  1720.  
  1721.       last_shell_builtin = this_shell_builtin;
  1722.       this_shell_builtin = builtin;
  1723.  
  1724.       if (builtin || func)
  1725.     {
  1726.       if ((pipe_in != NO_PIPE) || (pipe_out != NO_PIPE) || async)
  1727.         {
  1728.           if (make_child (savestring (command_line), async) == 0)
  1729.         {
  1730.           /* Cancel traps, in trap.c. */
  1731.           restore_original_signals ();
  1732.  
  1733.           if (async)
  1734.             setup_async_signals ();
  1735.  
  1736.           execute_subshell_builtin_or_function
  1737.             (words, simple_command->redirects, builtin, func,
  1738.              pipe_in, pipe_out, async, fds_to_close,
  1739.              simple_command->flags);
  1740.         }
  1741.           else
  1742.         {
  1743.           close_pipes (pipe_in, pipe_out);
  1744. #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
  1745.           unlink_fifo_list ();
  1746. #endif
  1747.           goto return_result;
  1748.         }
  1749.         }
  1750.       else
  1751.         {
  1752.           result = execute_builtin_or_function
  1753.         (words, builtin, func, simple_command->redirects, fds_to_close,
  1754.          simple_command->flags);
  1755.  
  1756.           goto return_result;
  1757.         }
  1758.     }
  1759.  
  1760.       execute_disk_command (words, simple_command->redirects, command_line,
  1761.                 pipe_in, pipe_out, async, fds_to_close,
  1762.                 (simple_command->flags & CMD_NO_FORK));
  1763.  
  1764.       goto return_result;
  1765.     }
  1766.   else if (pipe_in != NO_PIPE || pipe_out != NO_PIPE || async)
  1767.     {
  1768.       /* We have a null command, but we really want a subshell to take
  1769.      care of it.  Just fork, do piping and redirections, and exit. */
  1770.       if (make_child (savestring (""), async) == 0)
  1771.     {
  1772.       /* Cancel traps, in trap.c. */
  1773.       restore_original_signals ();
  1774.  
  1775.       do_piping (pipe_in, pipe_out);
  1776.  
  1777.       subshell_environment = 1;
  1778.  
  1779.       if (do_redirections (simple_command->redirects, 1, 0, 0) == 0)
  1780.         exit (EXECUTION_SUCCESS);
  1781.       else
  1782.         exit (EXECUTION_FAILURE);
  1783.     }
  1784.       else
  1785.     {
  1786.       close_pipes (pipe_in, pipe_out);
  1787. #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
  1788.       unlink_fifo_list ();
  1789. #endif
  1790.       result = EXECUTION_SUCCESS;
  1791.       goto return_result;
  1792.     }
  1793.     }
  1794.   else
  1795.     {
  1796.       /* Even if there aren't any command names, pretend to do the
  1797.      redirections that are specified.  The user expects the side
  1798.      effects to take place.  If the redirections fail, then return
  1799.      failure.  Otherwise, if a command substitution took place while
  1800.      expanding the command or a redirection, return the value of that
  1801.      substitution.  Otherwise, return EXECUTION_SUCCESS. */
  1802.  
  1803.       if (do_redirections (simple_command->redirects, 0, 0, 0) != 0)
  1804.     result = EXECUTION_FAILURE;
  1805.       else if (old_last_command_subst_pid != last_command_subst_pid)
  1806.     result = last_command_exit_value;
  1807.       else
  1808.     result = EXECUTION_SUCCESS;
  1809.     }
  1810.  
  1811.  return_result:
  1812.   bind_lastarg (lastarg);
  1813.   /* The unwind-protect frame is set up only if WORDS is not empty. */
  1814.   if (words)
  1815.     run_unwind_frame ("simple-command");
  1816.   return (result);
  1817. }
  1818.  
  1819. static int
  1820. execute_builtin (builtin, words, flags, subshell)
  1821.      Function *builtin;
  1822.      WORD_LIST *words;
  1823.      int flags, subshell;
  1824. {
  1825.   int old_e_flag = exit_immediately_on_error;
  1826.   int result;
  1827.  
  1828.   /* The eval builtin calls parse_and_execute, which does not know about
  1829.      the setting of flags, and always calls the execution functions with
  1830.      flags that will exit the shell on an error if -e is set.  If the
  1831.      eval builtin is being called, and we're supposed to ignore the exit
  1832.      value of the command, we turn the -e flag off ourselves, then
  1833.      restore it when the command completes. */
  1834.   if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
  1835.     {
  1836.       begin_unwind_frame ("eval_builtin");
  1837.       unwind_protect_int (exit_immediately_on_error);
  1838.       exit_immediately_on_error = 0;
  1839.     }
  1840.  
  1841.   /* The temporary environment for a builtin is supposed to apply to
  1842.      all commands executed by that builtin.  Currently, this is a
  1843.      problem only with the `source' builtin. */
  1844.   if (builtin == source_builtin)
  1845.     {
  1846.       if (subshell == 0)
  1847.     begin_unwind_frame ("builtin_env");
  1848.  
  1849.       if (temporary_env)
  1850.     {
  1851.       builtin_env = copy_array (temporary_env);
  1852.       if (subshell == 0)
  1853.         add_unwind_protect (dispose_builtin_env, (char *)NULL);
  1854.       dispose_used_env_vars ();
  1855.     }
  1856.       else
  1857.     builtin_env = (char **)NULL;
  1858.     }
  1859.  
  1860.   result = ((*builtin) (words->next));
  1861.  
  1862.   if (subshell == 0 && builtin == source_builtin)
  1863.     {
  1864.       dispose_builtin_env ();
  1865.       discard_unwind_frame ("builtin_env");
  1866.     }
  1867.  
  1868.   if (subshell == 0 && builtin == eval_builtin && (flags & CMD_IGNORE_RETURN))
  1869.     {
  1870.       exit_immediately_on_error += old_e_flag;
  1871.       discard_unwind_frame ("eval_builtin");
  1872.     }
  1873.  
  1874.   return (result);
  1875. }
  1876.  
  1877. /* XXX -- why do we need to set up unwind-protects for the case where
  1878.    subshell == 1 at all? */
  1879. static int
  1880. execute_function (var, words, flags, fds_to_close, async, subshell)
  1881.      SHELL_VAR *var;
  1882.      WORD_LIST *words;
  1883.      int flags, subshell, async;
  1884.      struct fd_bitmap *fds_to_close;
  1885. {
  1886.   int return_val, result;
  1887.   COMMAND *tc, *fc;
  1888.  
  1889.   tc = (COMMAND *)copy_command (function_cell (var));
  1890.   if (tc && (flags & CMD_IGNORE_RETURN))
  1891.     tc->flags |= CMD_IGNORE_RETURN;
  1892.  
  1893.   if (subshell)
  1894.     begin_unwind_frame ("subshell_function_calling");
  1895.   else
  1896.     begin_unwind_frame ("function_calling");
  1897.  
  1898.   if (subshell == 0)
  1899.     {
  1900.       push_context ();
  1901.       add_unwind_protect (pop_context, (char *)NULL);
  1902.       unwind_protect_int (line_number);
  1903.     }
  1904.   else
  1905.     unwind_protect_int (variable_context);
  1906.  
  1907.   unwind_protect_int (loop_level);
  1908.   unwind_protect_int (return_catch_flag);
  1909.   unwind_protect_jmp_buf (return_catch);
  1910.   add_unwind_protect (dispose_command, (char *)tc);
  1911.  
  1912.   /* The temporary environment for a function is supposed to apply to
  1913.      all commands executed within the function body. */
  1914.   if (temporary_env)
  1915.     {
  1916.       function_env = copy_array (temporary_env);
  1917.       add_unwind_protect (dispose_function_env, (char *)NULL);
  1918.       dispose_used_env_vars ();
  1919.     }
  1920.   else
  1921.     function_env = (char **)NULL;
  1922.  
  1923.   /* Note the second argument of "1", meaning that we discard
  1924.      the current value of "$*"!  This is apparently the right thing. */
  1925.   remember_args (words->next, 1);
  1926.  
  1927.   line_number = function_line_number = tc->line;
  1928.  
  1929.   if (subshell)
  1930.     {
  1931. #if defined (JOB_CONTROL)
  1932.       stop_pipeline (async, (COMMAND *)NULL);
  1933. #endif
  1934.       if (tc->type == cm_group)
  1935.     fc = tc->value.Group->command;
  1936.       else
  1937.     fc = tc;
  1938.  
  1939.       if (fc && (flags & CMD_IGNORE_RETURN))
  1940.     fc->flags |= CMD_IGNORE_RETURN;
  1941.  
  1942.       variable_context++;
  1943.     }
  1944.   else
  1945.     fc = tc;
  1946.  
  1947.   return_catch_flag++;
  1948.   return_val = setjmp (return_catch);
  1949.  
  1950.   if (return_val)
  1951.     result = return_catch_value;
  1952.   else
  1953.     result = execute_command_internal (fc, 0, NO_PIPE, NO_PIPE, fds_to_close);
  1954.  
  1955.   if (subshell)
  1956.     run_unwind_frame ("subshell_function_calling");
  1957.   else
  1958.     run_unwind_frame ("function_calling");
  1959.  
  1960.   return (result);
  1961. }
  1962.  
  1963. /* Execute a shell builtin or function in a subshell environment.  This
  1964.    routine does not return; it only calls exit().  If BUILTIN is non-null,
  1965.    it points to a function to call to execute a shell builtin; otherwise
  1966.    VAR points at the body of a function to execute.  WORDS is the arguments
  1967.    to the command, REDIRECTS specifies redirections to perform before the
  1968.    command is executed. */
  1969. static void
  1970. execute_subshell_builtin_or_function (words, redirects, builtin, var,
  1971.                       pipe_in, pipe_out, async, fds_to_close,
  1972.                       flags)
  1973.      WORD_LIST *words;
  1974.      REDIRECT *redirects;
  1975.      Function *builtin;
  1976.      SHELL_VAR *var;
  1977.      int pipe_in, pipe_out, async;
  1978.      struct fd_bitmap *fds_to_close;
  1979.      int flags;
  1980. {
  1981.   /* A subshell is neither a login shell nor interactive. */
  1982.   login_shell = interactive = 0;
  1983.  
  1984.   subshell_environment = 1;
  1985.  
  1986.   maybe_make_export_env ();
  1987.  
  1988. #if defined (JOB_CONTROL)
  1989.   /* Eradicate all traces of job control after we fork the subshell, so
  1990.      all jobs begun by this subshell are in the same process group as
  1991.      the shell itself. */
  1992.  
  1993.   /* Allow the output of `jobs' to be piped. */
  1994.   if (builtin == jobs_builtin && !async &&
  1995.       (pipe_out != NO_PIPE || pipe_in != NO_PIPE))
  1996.     kill_current_pipeline ();
  1997.   else
  1998.     without_job_control ();
  1999.  
  2000.   set_sigchld_handler ();
  2001. #endif /* JOB_CONTROL */
  2002.  
  2003.   set_sigint_handler ();
  2004.  
  2005.   do_piping (pipe_in, pipe_out);
  2006.  
  2007.   if (fds_to_close)
  2008.     close_fd_bitmap (fds_to_close);
  2009.  
  2010.   if (do_redirections (redirects, 1, 0, 0) != 0)
  2011.     exit (EXECUTION_FAILURE);
  2012.  
  2013.   if (builtin)
  2014.     {
  2015.       int result;
  2016.  
  2017.       /* Give builtins a place to jump back to on failure,
  2018.      so we don't go back up to main(). */
  2019.       result = setjmp (top_level);
  2020.  
  2021.       if (result == EXITPROG)
  2022.     exit (last_command_exit_value);
  2023.       else if (result)
  2024.     exit (EXECUTION_FAILURE);
  2025.       else
  2026.     exit (execute_builtin (builtin, words, flags, 1));
  2027.     }
  2028.   else
  2029.     {
  2030.       exit (execute_function (var, words, flags, fds_to_close, async, 1));
  2031.     }
  2032. }
  2033.  
  2034. /* Execute a builtin or function in the current shell context.  If BUILTIN
  2035.    is non-null, it is the builtin command to execute, otherwise VAR points
  2036.    to the body of a function.  WORDS are the command's arguments, REDIRECTS
  2037.    are the redirections to perform.  FDS_TO_CLOSE is the usual bitmap of
  2038.    file descriptors to close.
  2039.  
  2040.    If BUILTIN is exec_builtin, the redirections specified in REDIRECTS are
  2041.    not undone before this function returns. */
  2042. static int
  2043. execute_builtin_or_function (words, builtin, var, redirects,
  2044.                  fds_to_close, flags)
  2045.      WORD_LIST *words;
  2046.      Function *builtin;
  2047.      SHELL_VAR *var;
  2048.      REDIRECT *redirects;
  2049.      struct fd_bitmap *fds_to_close;
  2050.      int flags;
  2051. {
  2052.   int result = EXECUTION_FAILURE;
  2053.   REDIRECT *saved_undo_list;
  2054.  
  2055.   if (do_redirections (redirects, 1, 1, 0) != 0)
  2056.     {
  2057.       cleanup_redirects (redirection_undo_list);
  2058.       redirection_undo_list = (REDIRECT *)NULL;
  2059.       dispose_exec_redirects ();
  2060.       return (EXECUTION_FAILURE);
  2061.     }
  2062.  
  2063.   saved_undo_list = redirection_undo_list;
  2064.  
  2065.   /* Calling the "exec" builtin changes redirections forever. */
  2066.   if (builtin == exec_builtin)
  2067.     {
  2068.       dispose_redirects (saved_undo_list);
  2069.       saved_undo_list = exec_redirection_undo_list;
  2070.       exec_redirection_undo_list = (REDIRECT *)NULL;
  2071.     }
  2072.   else
  2073.     dispose_exec_redirects ();
  2074.  
  2075.   if (saved_undo_list)
  2076.     {
  2077.       begin_unwind_frame ("saved redirects");
  2078.       add_unwind_protect (cleanup_func_redirects, (char *)saved_undo_list);
  2079.       add_unwind_protect (dispose_redirects, (char *)saved_undo_list);
  2080.     }
  2081.  
  2082.   redirection_undo_list = (REDIRECT *)NULL;
  2083.  
  2084.   if (builtin)
  2085.     result = execute_builtin (builtin, words, flags, 0);
  2086.   else
  2087.     result = execute_function (var, words, flags, fds_to_close, 0, 0);
  2088.  
  2089.   if (saved_undo_list)
  2090.     {
  2091.       redirection_undo_list = saved_undo_list;
  2092.       discard_unwind_frame ("saved redirects");
  2093.     }
  2094.  
  2095.   if (redirection_undo_list)
  2096.     {
  2097.       do_redirections (redirection_undo_list, 1, 0, 0);
  2098.       dispose_redirects (redirection_undo_list);
  2099.       redirection_undo_list = (REDIRECT *)NULL;
  2100.     }
  2101.  
  2102.   return (result);
  2103. }
  2104.  
  2105. void
  2106. setup_async_signals ()
  2107. {
  2108. #if defined (JOB_CONTROL)
  2109.   if (job_control == 0)
  2110. #endif
  2111.     {
  2112.       set_signal_handler (SIGINT, SIG_IGN);
  2113.       set_signal_ignored (SIGINT);
  2114.       set_signal_handler (SIGQUIT, SIG_IGN);
  2115.       set_signal_ignored (SIGQUIT);
  2116.     }
  2117. }
  2118.  
  2119. /* Execute a simple command that is hopefully defined in a disk file
  2120.    somewhere.
  2121.  
  2122.    1) fork ()
  2123.    2) connect pipes
  2124.    3) look up the command
  2125.    4) do redirections
  2126.    5) execve ()
  2127.    6) If the execve failed, see if the file has executable mode set.
  2128.    If so, and it isn't a directory, then execute its contents as
  2129.    a shell script.
  2130.  
  2131.    Note that the filename hashing stuff has to take place up here,
  2132.    in the parent.  This is probably why the Bourne style shells
  2133.    don't handle it, since that would require them to go through
  2134.    this gnarly hair, for no good reason.  */
  2135. static void
  2136. execute_disk_command (words, redirects, command_line, pipe_in, pipe_out,
  2137.               async, fds_to_close, nofork)
  2138.      WORD_LIST *words;
  2139.      REDIRECT *redirects;
  2140.      char *command_line;
  2141.      int pipe_in, pipe_out, async;
  2142.      struct fd_bitmap *fds_to_close;
  2143.      int nofork;    /* Don't fork, just exec, if no pipes */
  2144. {
  2145.   register char *pathname;
  2146.   char *hashed_file, *command, **args;
  2147.   int pid, temp_path;
  2148.   SHELL_VAR *path;
  2149.  
  2150.   pathname = words->word->word;
  2151. #if defined (RESTRICTED_SHELL)
  2152.   if (restricted && strchr (pathname, '/'))
  2153.     {
  2154.       report_error ("%s: restricted: cannot specify `/' in command names",
  2155.             pathname);
  2156.       last_command_exit_value = EXECUTION_FAILURE;
  2157.       return;
  2158.     }
  2159. #endif /* RESTRICTED_SHELL */
  2160.  
  2161.   hashed_file = command = (char *)NULL;
  2162.  
  2163.   /* If PATH is in the temporary environment for this command, don't use the
  2164.      hash table to search for the full pathname. */
  2165.   temp_path = 0;
  2166.   path = find_tempenv_variable ("PATH");
  2167.   if (path)
  2168.     temp_path = 1;
  2169.  
  2170.   /* Don't waste time trying to find hashed data for a pathname
  2171.      that is already completely specified. */
  2172.  
  2173.   if (!path && !absolute_program (pathname))
  2174.     hashed_file = find_hashed_filename (pathname);
  2175.  
  2176.   /* If a command found in the hash table no longer exists, we need to
  2177.      look for it in $PATH.  Thank you Posix.2.  This forces us to stat
  2178.      every command found in the hash table.  It seems pretty stupid to me,
  2179.      so I am basing it on the presence of POSIXLY_CORRECT. */
  2180.  
  2181.   if (hashed_file && posixly_correct)
  2182.     {
  2183.       int st;
  2184.  
  2185.       st = file_status (hashed_file);
  2186.       if ((st ^ (FS_EXISTS | FS_EXECABLE)) != 0)
  2187.     {
  2188.       remove_hashed_filename (pathname);
  2189.       hashed_file = (char *)NULL;
  2190.     }
  2191.     }
  2192.  
  2193.   if (hashed_file)
  2194.     command = savestring (hashed_file);
  2195.   else if (absolute_program (pathname))
  2196.     /* A command containing a slash is not looked up in PATH or saved in
  2197.        the hash table. */
  2198.     command = savestring (pathname);
  2199.   else
  2200.     {
  2201.       command = find_user_command (pathname);
  2202.       if (command && !hashing_disabled && !temp_path)
  2203.     remember_filename (pathname, command, dot_found_in_search, 1);
  2204.     }
  2205.  
  2206.   maybe_make_export_env ();
  2207.  
  2208.   if (command)
  2209.     put_command_name_into_env (command);
  2210.  
  2211.   /* We have to make the child before we check for the non-existance
  2212.      of COMMAND, since we want the error messages to be redirected. */
  2213.   /* If we can get away without forking and there are no pipes to deal with,
  2214.      don't bother to fork, just directly exec the command. */
  2215.   if (nofork && pipe_in == NO_PIPE && pipe_out == NO_PIPE)
  2216.     pid = 0;
  2217.   else
  2218.     pid = make_child (savestring (command_line), async);
  2219.  
  2220.   if (pid == 0)
  2221.     {
  2222.       int old_interactive;
  2223.  
  2224.       /* Cancel traps, in trap.c. */
  2225.       restore_original_signals ();
  2226.  
  2227.       /* restore_original_signals may have undone the work done
  2228.          by make_child to ensure that SIGINT and SIGQUIT are ignored
  2229.          in asynchronous children. */
  2230.       if (async)
  2231.     setup_async_signals ();
  2232.  
  2233.       do_piping (pipe_in, pipe_out);
  2234.  
  2235.       /* Execve expects the command name to be in args[0].  So we
  2236.      leave it there, in the same format that the user used to
  2237.      type it in. */
  2238.       args = make_word_array (words);
  2239.  
  2240.       if (async)
  2241.     {
  2242.       old_interactive = interactive;
  2243.       interactive = 0;
  2244.     }
  2245.  
  2246.       subshell_environment = 1;
  2247.  
  2248.       /* This functionality is now provided by close-on-exec of the
  2249.      file descriptors manipulated by redirection and piping.
  2250.      Some file descriptors still need to be closed in all children
  2251.      because of the way bash does pipes; fds_to_close is a 
  2252.      bitmap of all such file descriptors. */
  2253.       if (fds_to_close)
  2254.     close_fd_bitmap (fds_to_close);
  2255.  
  2256.       if (redirects && (do_redirections (redirects, 1, 0, 0) != 0))
  2257.     {
  2258. #if defined (PROCESS_SUBSTITUTION)
  2259.       /* Try to remove named pipes that may have been created as the
  2260.          result of redirections. */
  2261.       unlink_fifo_list ();
  2262. #endif /* PROCESS_SUBSTITUTION */
  2263.       exit (EXECUTION_FAILURE);
  2264.     }
  2265.  
  2266.       if (async)
  2267.     interactive = old_interactive;
  2268.  
  2269.       if (!command)
  2270.     {
  2271.       report_error ("%s: command not found", args[0]);
  2272.       exit (EX_NOTFOUND);    /* Posix.2 says the exit status is 127 */
  2273.     }
  2274.  
  2275.       exit (shell_execve (command, args, export_env));
  2276.     }
  2277.   else
  2278.     {
  2279.       /* Make sure that the pipes are closed in the parent. */
  2280.       close_pipes (pipe_in, pipe_out);
  2281. #if defined (PROCESS_SUBSTITUTION) && defined (HAVE_DEV_FD)
  2282.       unlink_fifo_list ();
  2283. #endif
  2284.       FREE (command);
  2285.     }
  2286. }
  2287.  
  2288. /* If the operating system on which we're running does not handle
  2289.    the #! executable format, then help out.  SAMPLE is the text read
  2290.    from the file, SAMPLE_LEN characters.  COMMAND is the name of
  2291.    the script; it and ARGS, the arguments given by the user, will
  2292.    become arguments to the specified interpreter.  ENV is the environment
  2293.    to pass to the interpreter.
  2294.  
  2295.    The word immediately following the #! is the interpreter to execute.
  2296.    A single argument to the interpreter is allowed. */
  2297. static int
  2298. execute_shell_script (sample, sample_len, command, args, env)
  2299.      unsigned char *sample;
  2300.      int sample_len;
  2301.      char *command;
  2302.      char **args, **env;
  2303. {
  2304.   register int i;
  2305.   char *execname, *firstarg;
  2306.   int start, size_increment, larry;
  2307.  
  2308.   /* Find the name of the interpreter to exec. */
  2309.   for (i = 2; whitespace (sample[i]) && i < sample_len; i++)
  2310.     ;
  2311.  
  2312.   for (start = i;
  2313.        !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
  2314.        i++)
  2315.     ;
  2316.  
  2317.   execname = xmalloc (1 + (i - start));
  2318.   strncpy (execname, (char *) (sample + start), i - start);
  2319.   execname[i - start] = '\0';
  2320.   size_increment = 1;
  2321.  
  2322.   /* Now the argument, if any. */
  2323.   firstarg = (char *)NULL;
  2324.   for (start = i;
  2325.        whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
  2326.        i++)
  2327.     ;
  2328.  
  2329.   /* If there is more text on the line, then it is an argument for the
  2330.      interpreter. */
  2331.   if (i < sample_len && sample[i] != '\n' && !whitespace (sample[i]))
  2332.     {
  2333.       for (start = i;
  2334.        !whitespace (sample[i]) && sample[i] != '\n' && i < sample_len;
  2335.        i++)
  2336.     ;
  2337.       firstarg = xmalloc (1 + (i - start));
  2338.       strncpy (firstarg, (char *)(sample + start), i - start);
  2339.       firstarg[i - start] = '\0';
  2340.  
  2341.       size_increment = 2;
  2342.     }
  2343.  
  2344.   larry = array_len (args) + size_increment;
  2345.  
  2346.   args = (char **)xrealloc ((char *)args, (1 + larry) * sizeof (char *));
  2347.  
  2348.   for (i = larry - 1; i; i--)
  2349.     args[i] = args[i - size_increment];
  2350.  
  2351.   args[0] = execname;
  2352.   if (firstarg)
  2353.     {
  2354.       args[1] = firstarg;
  2355.       args[2] = command;
  2356.     }
  2357.   else
  2358.     args[1] = command;
  2359.  
  2360.   args[larry] = (char *)NULL;
  2361.  
  2362.   return (shell_execve (execname, args, env));
  2363. }
  2364.  
  2365. /* Call execve (), handling interpreting shell scripts, and handling
  2366.    exec failures. */
  2367. int
  2368. shell_execve (command, args, env)
  2369.      char *command;
  2370.      char **args, **env;
  2371. {
  2372. #if defined (isc386) && defined (_POSIX_SOURCE)
  2373.   __setostype (0);        /* Turn on USGr3 semantics. */
  2374.   execve (command, args, env);
  2375.   __setostype (1);        /* Turn the POSIX semantics back on. */
  2376. #else
  2377.   execve (command, args, env);
  2378. #endif /* !(isc386 && _POSIX_SOURCE) */
  2379.  
  2380.   /* If we get to this point, then start checking out the file.
  2381.      Maybe it is something we can hack ourselves. */
  2382.   {
  2383.     struct stat finfo;
  2384.  
  2385.     if (errno != ENOEXEC)
  2386.       {
  2387.     if ((stat (command, &finfo) == 0) &&
  2388.         (S_ISDIR (finfo.st_mode)))
  2389.       report_error ("%s: is a directory", args[0]);
  2390.     else
  2391.       file_error (command);
  2392.  
  2393.     return (EX_NOEXEC);    /* XXX Posix.2 says that exit status is 126 */
  2394.       }
  2395.     else
  2396.       {
  2397.     /* This file is executable.
  2398.        If it begins with #!, then help out people with losing operating
  2399.        systems.  Otherwise, check to see if it is a binary file by seeing
  2400.        if the first line (or up to 30 characters) are in the ASCII set.
  2401.        Execute the contents as shell commands. */
  2402.     int larray = array_len (args) + 1;
  2403.     int i, should_exec = 0;
  2404.  
  2405.     {
  2406.       int fd = open (command, O_RDONLY);
  2407.       if (fd != -1)
  2408.         {
  2409.           unsigned char sample[80];
  2410.           int sample_len = read (fd, &sample[0], 80);
  2411.  
  2412.           close (fd);
  2413.  
  2414.           if (sample_len == 0)
  2415.         return (EXECUTION_SUCCESS);
  2416.  
  2417.           /* Is this supposed to be an executable script?
  2418.              If so, the format of the line is "#! interpreter [argument]".
  2419.          A single argument is allowed.  The BSD kernel restricts
  2420.          the length of the entire line to 32 characters (32 bytes
  2421.          being the size of the BSD exec header), but we allow 80
  2422.          characters. */
  2423.  
  2424.           if (sample_len > 0 && sample[0] == '#' && sample[1] == '!')
  2425.         return (execute_shell_script
  2426.             (sample, sample_len, command, args, env));
  2427.           else if ((sample_len != -1) &&
  2428.                check_binary_file (sample, sample_len))
  2429.         {
  2430.           report_error ("%s: cannot execute binary file", command);
  2431.           return (EX_BINARY_FILE);
  2432.         }
  2433.         }
  2434.     }
  2435. #if defined (JOB_CONTROL)
  2436.     /* Forget about the way that job control was working. We are
  2437.        in a subshell. */
  2438.     without_job_control ();
  2439. #endif /* JOB_CONTROL */
  2440. #if defined (ALIAS)
  2441.     /* Forget about any aliases that we knew of.  We are in a subshell. */
  2442.     delete_all_aliases ();
  2443. #endif /* ALIAS */
  2444.  
  2445. #if defined (JOB_CONTROL)
  2446.     set_sigchld_handler ();
  2447. #endif /* JOB_CONTROL */
  2448.     set_sigint_handler ();
  2449.  
  2450.     /* Insert the name of this shell into the argument list. */
  2451.     args = (char **)xrealloc ((char *)args, (1 + larray) * sizeof (char *));
  2452.  
  2453.     for (i = larray - 1; i; i--)
  2454.       args[i] = args[i - 1];
  2455.  
  2456.     args[0] = shell_name;
  2457.     args[1] = command;
  2458.     args[larray] = (char *)NULL;
  2459.  
  2460.     if (args[0][0] == '-')
  2461.       args[0]++;
  2462.  
  2463.     if (should_exec)
  2464.       {
  2465.         struct stat finfo;
  2466.  
  2467. #if defined (isc386) && defined (_POSIX_SOURCE)
  2468.         __setostype (0);    /* Turn on USGr3 semantics. */
  2469.         execve (shell_name, args, env);
  2470.         __setostype (1);    /* Turn the POSIX semantics back on. */
  2471. #else
  2472.         execve (shell_name, args, env);
  2473. #endif /* isc386 && _POSIX_SOURCE */
  2474.  
  2475.         /* Oh, no!  We couldn't even exec this! */
  2476.         if ((stat (args[0], &finfo) == 0) && (S_ISDIR (finfo.st_mode)))
  2477.           report_error ("%s: is a directory", args[0]);
  2478.         else
  2479.           file_error (args[0]);
  2480.  
  2481.         return (EXECUTION_FAILURE);
  2482.       }
  2483.     else
  2484.       {
  2485.         subshell_argc = larray;
  2486.         subshell_argv = args;
  2487.         subshell_envp = env;
  2488.         longjmp (subshell_top_level, 1);
  2489.       }
  2490.       }
  2491.   }
  2492. }
  2493.  
  2494. #if defined (PROCESS_SUBSTITUTION)
  2495. /* Currently unused */
  2496. void
  2497. close_all_files ()
  2498. {
  2499.   register int i, fd_table_size;
  2500.  
  2501.   fd_table_size = getdtablesize ();
  2502.   if (fd_table_size > 256)    /* clamp to a reasonable value */
  2503.       fd_table_size = 256;
  2504.  
  2505.   for (i = 3; i < fd_table_size; i++)
  2506.     close (i);
  2507. }
  2508. #endif /* PROCESS_SUBSTITUTION */
  2509.  
  2510. static void
  2511. close_pipes (in, out)
  2512.      int in, out;
  2513. {
  2514.   if (in >= 0)
  2515.     close (in);
  2516.   if (out >= 0)
  2517.     close (out);
  2518. }
  2519.  
  2520. /* Redirect input and output to be from and to the specified pipes.
  2521.    NO_PIPE and REDIRECT_BOTH are handled correctly. */
  2522. static void
  2523. do_piping (pipe_in, pipe_out)
  2524.      int pipe_in, pipe_out;
  2525. {
  2526.   if (pipe_in != NO_PIPE)
  2527.     {
  2528.       if (dup2 (pipe_in, 0) < 0)
  2529.     internal_error ("cannot duplicate fd %d to fd 0: %s",
  2530.             pipe_in, strerror (errno));
  2531.       if (pipe_in > 0)
  2532.         close (pipe_in);
  2533.     }
  2534.   if (pipe_out != NO_PIPE)
  2535.     {
  2536.       if (pipe_out != REDIRECT_BOTH)
  2537.     {
  2538.       if (dup2 (pipe_out, 1) < 0)
  2539.         internal_error ("cannot duplicate fd %d to fd 1: %s",
  2540.                 pipe_out, strerror (errno));
  2541.       if (pipe_out == 0 || pipe_out > 1)
  2542.         close (pipe_out);
  2543.     }
  2544.       else
  2545.     dup2 (1, 2);
  2546.     }
  2547. }
  2548.  
  2549. #define AMBIGUOUS_REDIRECT  -1
  2550. #define NOCLOBBER_REDIRECT  -2
  2551. #define RESTRICTED_REDIRECT -3    /* Only can happen in restricted shells. */
  2552.  
  2553. /* Perform the redirections on LIST.  If FOR_REAL, then actually make
  2554.    input and output file descriptors, otherwise just do whatever is
  2555.    neccessary for side effecting.  INTERNAL says to remember how to
  2556.    undo the redirections later, if non-zero.  If SET_CLEXEC is non-zero,
  2557.    file descriptors opened in do_redirection () have their close-on-exec
  2558.    flag set. */
  2559. static int
  2560. do_redirections (list, for_real, internal, set_clexec)
  2561.      REDIRECT *list;
  2562.      int for_real, internal, set_clexec;
  2563. {
  2564.   register int error;
  2565.   register REDIRECT *temp = list;
  2566.  
  2567.   if (internal)
  2568.     {
  2569.       if (redirection_undo_list)
  2570.     {
  2571.       dispose_redirects (redirection_undo_list);
  2572.       redirection_undo_list = (REDIRECT *)NULL;
  2573.     }
  2574.       if (exec_redirection_undo_list)
  2575.     dispose_exec_redirects ();
  2576.     }
  2577.  
  2578.   while (temp)
  2579.     {
  2580.       error = do_redirection_internal (temp, for_real, internal, set_clexec);
  2581.  
  2582.       if (error)
  2583.     {
  2584.       char *filename;
  2585.  
  2586.       if (expandable_redirection_filename (temp))
  2587.         {
  2588.           if (posixly_correct && !interactive_shell)
  2589.             disallow_filename_globbing++;
  2590.           filename = redirection_expand (temp->redirectee.filename);
  2591.           if (posixly_correct && !interactive_shell)
  2592.             disallow_filename_globbing--;
  2593.  
  2594.           if (!filename)
  2595.         filename = savestring ("");
  2596.         }
  2597.       else
  2598.         filename = itos (temp->redirectee.dest);
  2599.  
  2600.       switch (error)
  2601.         {
  2602.         case AMBIGUOUS_REDIRECT:
  2603.           report_error ("%s: Ambiguous redirect", filename);
  2604.           break;
  2605.  
  2606.         case NOCLOBBER_REDIRECT:
  2607.           report_error ("%s: Cannot clobber existing file", filename);
  2608.           break;
  2609.  
  2610. #if defined (RESTRICTED_SHELL)
  2611.         case RESTRICTED_REDIRECT:
  2612.           report_error ("%s: output redirection restricted", filename);
  2613.           break;
  2614. #endif /* RESTRICTED_SHELL */
  2615.  
  2616.         default:
  2617.           report_error ("%s: %s", filename, strerror (error));
  2618.           break;
  2619.         }
  2620.  
  2621.       free (filename);
  2622.       return (error);
  2623.     }
  2624.  
  2625.       temp = temp->next;
  2626.     }
  2627.   return (0);
  2628. }
  2629.  
  2630. /* Return non-zero if the redirection pointed to by REDIRECT has a
  2631.    redirectee.filename that can be expanded. */
  2632. static int
  2633. expandable_redirection_filename (redirect)
  2634.      REDIRECT *redirect;
  2635. {
  2636.   int result;
  2637.  
  2638.   switch (redirect->instruction)
  2639.     {
  2640.     case r_output_direction:
  2641.     case r_appending_to:
  2642.     case r_input_direction:
  2643.     case r_inputa_direction:
  2644.     case r_err_and_out:
  2645.     case r_input_output:
  2646.     case r_output_force:
  2647.     case r_duplicating_input_word:
  2648.     case r_duplicating_output_word:
  2649.       result = 1;
  2650.       break;
  2651.  
  2652.     default:
  2653.       result = 0;
  2654.     }
  2655.   return (result);
  2656. }
  2657.  
  2658. /* Expand the word in WORD returning a string.  If WORD expands to
  2659.    multiple words (or no words), then return NULL. */
  2660. char *
  2661. redirection_expand (word)
  2662.      WORD_DESC *word;
  2663. {
  2664.   char *result;
  2665.   WORD_LIST *tlist1, *tlist2;
  2666.  
  2667.   tlist1 = make_word_list (copy_word (word), (WORD_LIST *)NULL);
  2668.   tlist2 = expand_words_no_vars (tlist1);
  2669.   dispose_words (tlist1);
  2670.  
  2671.   if (!tlist2 || tlist2->next)
  2672.     {
  2673.       /* We expanded to no words, or to more than a single word.
  2674.      Dispose of the word list and return NULL. */
  2675.       if (tlist2)
  2676.     dispose_words (tlist2);
  2677.       return ((char *)NULL);
  2678.     }
  2679.   result = string_list (tlist2);
  2680.   dispose_words (tlist2);
  2681.   return (result);
  2682. }
  2683.  
  2684. /* Do the specific redirection requested.  Returns errno in case of error.
  2685.    If FOR_REAL is zero, then just do whatever is neccessary to produce the
  2686.    appropriate side effects.   REMEMBERING, if non-zero, says to remember
  2687.    how to undo each redirection.  If SET_CLEXEC is non-zero, then
  2688.    we set all file descriptors > 2 that we open to be close-on-exec.  */
  2689. static int
  2690. do_redirection_internal (redirect, for_real, remembering, set_clexec)
  2691.      REDIRECT *redirect;
  2692.      int for_real, remembering, set_clexec;
  2693. {
  2694.   WORD_DESC *redirectee = redirect->redirectee.filename;
  2695.   int redir_fd = redirect->redirectee.dest;
  2696.   int fd, redirector = redirect->redirector;
  2697.   char *redirectee_word;
  2698.   enum r_instruction ri = redirect->instruction;
  2699.   REDIRECT *new_redirect;
  2700.  
  2701.   if (ri == r_duplicating_input_word || ri == r_duplicating_output_word)
  2702.     {
  2703.       /* We have [N]>&WORD or [N]<&WORD.  Expand WORD, then translate
  2704.      the redirection into a new one and continue. */
  2705.       redirectee_word = redirection_expand (redirectee);
  2706.  
  2707.       if (redirectee_word[0] == '-' && redirectee_word[1] == '\0')
  2708.     {
  2709.       rd.dest = 0L;
  2710.       new_redirect = make_redirection (redirector, r_close_this, rd);
  2711.     }
  2712.       else if (all_digits (redirectee_word))
  2713.     {
  2714.       if (ri == r_duplicating_input_word)
  2715.         {
  2716.           rd.dest = atol (redirectee_word);
  2717.           new_redirect = make_redirection (redirector, r_duplicating_input, rd);
  2718.         }
  2719.       else
  2720.         {
  2721.           rd.dest = atol (redirectee_word);
  2722.           new_redirect = make_redirection (redirector, r_duplicating_output, rd);
  2723.         }
  2724.     }
  2725.       else if (ri == r_duplicating_output_word && redirector == 1)
  2726.     {
  2727.       if (!posixly_correct)
  2728.         {
  2729.           rd.filename = make_word (redirectee_word);
  2730.           new_redirect = make_redirection (1, r_err_and_out, rd);
  2731.         }
  2732.       else
  2733.         new_redirect = copy_redirect (redirect);
  2734.     }
  2735.       else
  2736.     {
  2737.       free (redirectee_word);
  2738.       return (AMBIGUOUS_REDIRECT);
  2739.     }
  2740.  
  2741.       free (redirectee_word);
  2742.  
  2743.       /* Set up the variables needed by the rest of the function from the
  2744.      new redirection. */
  2745.       if (new_redirect->instruction == r_err_and_out)
  2746.     {
  2747.       char *alloca_hack;
  2748.  
  2749.       /* Copy the word without allocating any memory that must be
  2750.          explicitly freed. */
  2751.       redirectee = (WORD_DESC *)alloca (sizeof (WORD_DESC));
  2752.       xbcopy ((char *)new_redirect->redirectee.filename,
  2753.          (char *)redirectee, sizeof (WORD_DESC));
  2754.  
  2755.       alloca_hack = (char *)
  2756.         alloca (1 + strlen (new_redirect->redirectee.filename->word));
  2757.       redirectee->word = alloca_hack;
  2758.       strcpy (redirectee->word, new_redirect->redirectee.filename->word);
  2759.     }
  2760.       else
  2761.     /* It's guaranteed to be an integer, and shouldn't be freed. */
  2762.     redirectee = new_redirect->redirectee.filename;
  2763.  
  2764.       redir_fd = new_redirect->redirectee.dest;
  2765.       redirector = new_redirect->redirector;
  2766.       ri = new_redirect->instruction;
  2767.  
  2768.       /* Overwrite the flags element of the old redirect with the new value. */
  2769.       redirect->flags = new_redirect->flags;
  2770.       dispose_redirects (new_redirect);
  2771.     }
  2772.  
  2773.   switch (ri)
  2774.     {
  2775.     case r_output_direction:
  2776.     case r_appending_to:
  2777.     case r_input_direction:
  2778.     case r_inputa_direction:
  2779.     case r_err_and_out:        /* command &>filename */
  2780.     case r_input_output:
  2781.     case r_output_force:
  2782.  
  2783.       if (posixly_correct && !interactive_shell)
  2784.     disallow_filename_globbing++;
  2785.       redirectee_word = redirection_expand (redirectee);
  2786.       if (posixly_correct && !interactive_shell)
  2787.     disallow_filename_globbing--;
  2788.       
  2789.       if (!redirectee_word)
  2790.     return (AMBIGUOUS_REDIRECT);
  2791.  
  2792. #if defined (RESTRICTED_SHELL)
  2793.       if (restricted && (ri == r_output_direction ||
  2794.              ri == r_input_output ||
  2795.              ri == r_err_and_out ||
  2796.              ri == r_appending_to ||
  2797.              ri == r_output_force))
  2798.     {
  2799.       free (redirectee_word);
  2800.       return (RESTRICTED_REDIRECT);
  2801.     }
  2802. #endif /* RESTRICTED_SHELL */
  2803.  
  2804.       /* If we are in noclobber mode, you are not allowed to overwrite
  2805.      existing files.  Check first. */
  2806.       if (noclobber && (ri == r_output_direction ||
  2807.               ri == r_input_output ||
  2808.               ri == r_err_and_out))
  2809.     {
  2810.       struct stat finfo;
  2811.       int stat_result;
  2812.  
  2813.       stat_result = stat (redirectee_word, &finfo);
  2814.  
  2815.       if ((stat_result == 0) && (S_ISREG (finfo.st_mode)))
  2816.         {
  2817.           free (redirectee_word);
  2818.           return (NOCLOBBER_REDIRECT);
  2819.         }
  2820.  
  2821.       /* If the file was not present, make sure we open it exclusively
  2822.          so that if it is created before we open it, our open will fail. */
  2823.       if (stat_result != 0)
  2824.         redirect->flags |= O_EXCL;
  2825.  
  2826.       fd = open (redirectee_word, redirect->flags, 0666);
  2827.  
  2828.       if ((fd < 0) && (errno == EEXIST))
  2829.         {
  2830.           free (redirectee_word);
  2831.           return (NOCLOBBER_REDIRECT);
  2832.         }
  2833.     }
  2834.       else
  2835.     {
  2836.       fd = open (redirectee_word, redirect->flags, 0666);
  2837. #if defined (AFS_CREATE_BUG)
  2838.       if ((fd < 0) && (errno == EACCES))
  2839.         fd = open (redirectee_word, (redirect->flags & ~O_CREAT), 0666);
  2840. #endif /* AFS_CREATE_BUG */
  2841.     }
  2842.       free (redirectee_word);
  2843.  
  2844.       if (fd < 0)
  2845.     return (errno);
  2846.  
  2847.       if (for_real)
  2848.     {
  2849.       if (remembering)
  2850.         /* Only setup to undo it if the thing to undo is active. */
  2851.         if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
  2852.           add_undo_redirect (redirector);
  2853.         else
  2854.           add_undo_close_redirect (redirector);
  2855.  
  2856. #if defined (BUFFERED_INPUT)
  2857.       check_bash_input (redirector);
  2858. #endif
  2859.  
  2860.       if ((fd != redirector) && (dup2 (fd, redirector) < 0))
  2861.         return (errno);
  2862.  
  2863. #if defined (BUFFERED_INPUT)
  2864.       /* Do not change the buffered stream for an implicit redirection
  2865.          of /dev/null to fd 0 for asynchronous commands without job
  2866.          control (r_inputa_direction). */
  2867.       if (ri == r_input_direction || ri == r_input_output)
  2868.         duplicate_buffered_stream (fd, redirector);
  2869. #endif /* BUFFERED_INPUT */
  2870.  
  2871.       /*
  2872.        * If we're remembering, then this is the result of a while, for
  2873.        * or until loop with a loop redirection, or a function/builtin
  2874.        * executing in the parent shell with a redirection.  In the
  2875.        * function/builtin case, we want to set all file descriptors > 2
  2876.        * to be close-on-exec to duplicate the effect of the old
  2877.        * for i = 3 to NOFILE close(i) loop.  In the case of the loops,
  2878.        * both sh and ksh leave the file descriptors open across execs.
  2879.        * The Posix standard mentions only the exec builtin.
  2880.        */
  2881.       if (set_clexec && (redirector > 2))
  2882.         SET_CLOSE_ON_EXEC (redirector);
  2883.     }
  2884.  
  2885.       if (fd != redirector)
  2886.     {
  2887. #if defined (BUFFERED_INPUT)
  2888.       if (ri == r_input_direction || ri == r_inputa_direction ||
  2889.           ri == r_input_output)
  2890.         close_buffered_fd (fd);
  2891.       else
  2892. #endif /* !BUFFERED_INPUT */
  2893.         close (fd);        /* Don't close what we just opened! */
  2894.     }
  2895.  
  2896.       /* If we are hacking both stdout and stderr, do the stderr
  2897.      redirection here. */
  2898.       if (ri == r_err_and_out)
  2899.     {
  2900.       if (for_real)
  2901.         {
  2902.           if (remembering)
  2903.         add_undo_redirect (2);
  2904.           if (dup2 (1, 2) < 0)
  2905.         return (errno);
  2906.         }
  2907.     }
  2908.       break;
  2909.  
  2910.     case r_reading_until:
  2911.     case r_deblank_reading_until:
  2912.       /* REDIRECTEE is a pointer to a WORD_DESC containing the text of
  2913.      the new input.  Place it in a temporary file. */
  2914.       if (redirectee)
  2915.     {
  2916.       char filename[40];
  2917.       pid_t pid = getpid ();
  2918.  
  2919.       /* Make the filename for the temp file. */
  2920.       sprintf (filename, "/tmp/t%d-sh", pid);
  2921.  
  2922.       fd = open (filename, O_TRUNC | O_WRONLY | O_CREAT, 0666);
  2923.       if (fd < 0)
  2924.         return (errno);
  2925.  
  2926.       errno = 0;        /* XXX */
  2927.       if (redirectee->word)
  2928.         {
  2929.           char *document;
  2930.           int document_len;
  2931.  
  2932.           /* Expand the text if the word that was specified had
  2933.          no quoting.  The text that we expand is treated
  2934.          exactly as if it were surrounded by double quotes. */
  2935.  
  2936.           if (redirectee->quoted)
  2937.         {
  2938.           document = redirectee->word;
  2939.           document_len = strlen (document);
  2940.           /* Set errno to something reasonable if the write fails. */
  2941.           if (write (fd, document, document_len) < document_len)
  2942.             {
  2943.               if (errno == 0)
  2944.             errno = ENOSPC;
  2945.               close (fd);
  2946.               return (errno);
  2947.             }
  2948.         }
  2949.           else
  2950.         {
  2951.           WORD_LIST *tlist;
  2952.           tlist = expand_string (redirectee->word, Q_HERE_DOCUMENT);
  2953.           if (tlist)
  2954.             {
  2955.               int fd2;
  2956.               FILE *fp;
  2957.               register WORD_LIST *t;
  2958.  
  2959.               /* Try using buffered I/O (stdio) and writing a word
  2960.              at a time, letting stdio do the work of buffering
  2961.              for us rather than managing our own strings.  Most
  2962.              stdios are not particularly fast, however -- this
  2963.              may need to be reconsidered later. */
  2964.               if ((fd2 = dup (fd)) < 0 ||
  2965.               (fp = fdopen (fd2, "w")) == NULL)
  2966.             {
  2967.               if (fd2 >= 0)
  2968.                 close (fd2);
  2969.               close (fd);
  2970.               return (errno);
  2971.             }
  2972.               errno = 0;    /* XXX */
  2973.               for (t = tlist; t; t = t->next)
  2974.             {
  2975.               /* This is essentially the body of
  2976.                  string_list_internal expanded inline. */
  2977.               document = t->word->word;
  2978.               document_len = strlen (document);
  2979.               if (t != tlist)
  2980.                 putc (' ', fp);    /* separator */
  2981.               fwrite (document, document_len, 1, fp);
  2982.               if (ferror (fp))
  2983.                 {
  2984.                   if (errno == 0)
  2985.                 errno = ENOSPC;
  2986.                   break;
  2987.                 }
  2988.             }
  2989.               fclose (fp);
  2990.               dispose_words (tlist);
  2991.             }
  2992.         }
  2993.         }      
  2994.  
  2995.       close (fd);
  2996.       if (errno)
  2997.         return (errno);
  2998.  
  2999.       /* Make the document really temporary.  Also make it the input. */
  3000.       fd = open (filename, O_RDONLY, 0666);
  3001.  
  3002.       if (unlink (filename) < 0 || fd < 0)
  3003.         {
  3004.           if (fd >= 0)
  3005.             close (fd);
  3006.           return (errno);
  3007.         }
  3008.  
  3009.       if (for_real)
  3010.         {
  3011.           if (remembering)
  3012.         /* Only setup to undo it if the thing to undo is active. */
  3013.         if ((fd != redirector) && (fcntl (redirector, F_GETFD, 0) != -1))
  3014.           add_undo_redirect (redirector);
  3015.         else
  3016.           add_undo_close_redirect (redirector);
  3017.  
  3018. #if defined (BUFFERED_INPUT)
  3019.           check_bash_input (redirector);
  3020. #endif
  3021.           if (dup2 (fd, redirector) < 0)
  3022.         {
  3023.           close (fd);
  3024.           return (errno);
  3025.         }
  3026.  
  3027. #if defined (BUFFERED_INPUT)
  3028.           duplicate_buffered_stream (fd, redirector);
  3029. #endif
  3030.  
  3031.           if (set_clexec && (redirector > 2))
  3032.         SET_CLOSE_ON_EXEC (redirector);
  3033.         }
  3034.  
  3035. #if defined (BUFFERED_INPUT)
  3036.       close_buffered_fd (fd);
  3037. #else
  3038.       close (fd);
  3039. #endif
  3040.     }
  3041.       break;
  3042.  
  3043.     case r_duplicating_input:
  3044.     case r_duplicating_output:
  3045.       if (for_real && (redir_fd != redirector))
  3046.     {
  3047.       if (remembering)
  3048.         /* Only setup to undo it if the thing to undo is active. */
  3049.         if (fcntl (redirector, F_GETFD, 0) != -1)
  3050.           add_undo_redirect (redirector);
  3051.         else
  3052.           add_undo_close_redirect (redirector);
  3053.  
  3054. #if defined (BUFFERED_INPUT)
  3055.       check_bash_input (redirector);
  3056. #endif
  3057.       /* This is correct.  2>&1 means dup2 (1, 2); */
  3058.       if (dup2 (redir_fd, redirector) < 0)
  3059.         return (errno);
  3060.  
  3061. #if defined (BUFFERED_INPUT)
  3062.       if (ri == r_duplicating_input)
  3063.         duplicate_buffered_stream (redir_fd, redirector);
  3064. #endif /* BUFFERED_INPUT */
  3065.  
  3066.       /* First duplicate the close-on-exec state of redirectee.  dup2
  3067.          leaves the flag unset on the new descriptor, which means it
  3068.          stays open.  Only set the close-on-exec bit for file descriptors
  3069.          greater than 2 in any case, since 0-2 should always be open
  3070.          unless closed by something like `exec 2<&-'. */
  3071.       /* if ((already_set || set_unconditionally) && (ok_to_set))
  3072.         set_it () */
  3073.       if (((fcntl (redir_fd, F_GETFD, 0) == 1) || set_clexec) &&
  3074.            (redirector > 2))
  3075.         SET_CLOSE_ON_EXEC (redirector);
  3076.     }
  3077.       break;
  3078.  
  3079.     case r_close_this:
  3080.       if (for_real)
  3081.     {
  3082.       if (remembering && (fcntl (redirector, F_GETFD, 0) != -1))
  3083.         add_undo_redirect (redirector);
  3084.  
  3085. #if defined (BUFFERED_INPUT)
  3086.       check_bash_input (redirector);
  3087.       close_buffered_fd (redirector);
  3088. #else /* !BUFFERED_INPUT */
  3089.       close (redirector);
  3090. #endif /* !BUFFERED_INPUT */
  3091.     }
  3092.       break;
  3093.     }
  3094.   return (0);
  3095. }
  3096.  
  3097. #define SHELL_FD_BASE    10
  3098.  
  3099. /* Remember the file descriptor associated with the slot FD,
  3100.    on REDIRECTION_UNDO_LIST.  Note that the list will be reversed
  3101.    before it is executed.  Any redirections that need to be undone
  3102.    even if REDIRECTION_UNDO_LIST is discarded by the exec builtin
  3103.    are also saved on EXEC_REDIRECTION_UNDO_LIST. */
  3104. static int
  3105. add_undo_redirect (fd)
  3106.      int fd;
  3107. {
  3108.   int new_fd, clexec_flag;
  3109.   REDIRECT *new_redirect, *closer;
  3110.  
  3111.   new_fd = fcntl (fd, F_DUPFD, SHELL_FD_BASE);
  3112.  
  3113.   if (new_fd < 0)
  3114.     {
  3115.       file_error ("redirection error");
  3116.       return (-1);
  3117.     }
  3118.   else
  3119.     {
  3120.       REDIRECT *dummy_redirect;
  3121.  
  3122.       clexec_flag = fcntl (fd, F_GETFD, 0);
  3123.  
  3124.       rd.dest = 0L;
  3125.       closer = make_redirection (new_fd, r_close_this, rd);
  3126.       dummy_redirect = copy_redirects (closer);
  3127.  
  3128.       rd.dest = (long)new_fd;
  3129.       new_redirect = make_redirection (fd, r_duplicating_output, rd);
  3130.       new_redirect->next = closer;
  3131.  
  3132.       closer->next = redirection_undo_list;
  3133.       redirection_undo_list = new_redirect;
  3134.  
  3135.       /* Save redirections that need to be undone even if the undo list
  3136.      is thrown away by the `exec' builtin. */
  3137.       add_exec_redirect (dummy_redirect);
  3138.  
  3139.       /* File descriptors used only for saving others should always be
  3140.      marked close-on-exec.  Unfortunately, we have to preserve the
  3141.      close-on-exec state of the file descriptor we are saving, since
  3142.      fcntl (F_DUPFD) sets the new file descriptor to remain open
  3143.      across execs.  If, however, the file descriptor whose state we
  3144.      are saving is <= 2, we can just set the close-on-exec flag,
  3145.      because file descriptors 0-2 should always be open-on-exec,
  3146.      and the restore above in do_redirection() will take care of it. */
  3147.       if (clexec_flag || fd < 3)
  3148.     SET_CLOSE_ON_EXEC (new_fd);
  3149.     }
  3150.   return (0);
  3151. }
  3152.  
  3153. /* Set up to close FD when we are finished with the current command
  3154.    and its redirections. */
  3155. static void
  3156. add_undo_close_redirect (fd)
  3157.      int fd;
  3158. {
  3159.   REDIRECT *closer;
  3160.  
  3161.   rd.dest = 0L;
  3162.   closer = make_redirection (fd, r_close_this, rd);
  3163.   closer->next = redirection_undo_list;
  3164.   redirection_undo_list = closer;
  3165. }
  3166.  
  3167. static void
  3168. add_exec_redirect (dummy_redirect)
  3169.      REDIRECT *dummy_redirect;
  3170. {
  3171.   dummy_redirect->next = exec_redirection_undo_list;
  3172.   exec_redirection_undo_list = dummy_redirect;
  3173. }
  3174.  
  3175. intern_function (name, function)
  3176.      WORD_DESC *name;
  3177.      COMMAND *function;
  3178. {
  3179.   SHELL_VAR *var;
  3180.  
  3181.   if (!check_identifier (name, posixly_correct))
  3182.     return (EXECUTION_FAILURE);
  3183.  
  3184.   var = find_function (name->word);
  3185.   if (var && readonly_p (var))
  3186.     {
  3187.       report_error ("%s: readonly function", var->name);
  3188.       return (EXECUTION_FAILURE);
  3189.     }
  3190.  
  3191.   bind_function (name->word, function);
  3192.   return (EXECUTION_SUCCESS);
  3193. }
  3194.  
  3195. #define u_mode_bits(x) (((x) & 0000700) >> 6)
  3196. #define g_mode_bits(x) (((x) & 0000070) >> 3)
  3197. #define o_mode_bits(x) (((x) & 0000007) >> 0)
  3198. #define X_BIT(x) ((x) & 1)
  3199.  
  3200. /* Return some flags based on information about this file.
  3201.    The EXISTS bit is non-zero if the file is found.
  3202.    The EXECABLE bit is non-zero the file is executble.
  3203.    Zero is returned if the file is not found. */
  3204. int
  3205. file_status (name)
  3206.      char *name;
  3207. {
  3208.   struct stat finfo;
  3209.   static int user_id = -1;
  3210.  
  3211.   /* Determine whether this file exists or not. */
  3212.   if (stat (name, &finfo) < 0)
  3213.     return (0);
  3214.  
  3215.   /* If the file is a directory, then it is not "executable" in the
  3216.      sense of the shell. */
  3217.   if (S_ISDIR (finfo.st_mode))
  3218.     return (FS_EXISTS);
  3219.  
  3220. #if defined (AFS)
  3221.   /* We have to use access(2) to determine access because AFS does not
  3222.      support Unix file system semantics.  This may produce wrong
  3223.      answers for non-AFS files when ruid != euid.  I hate AFS. */
  3224.   if (access (name, X_OK))
  3225.     return (FS_EXISTS | FS_EXECABLE);
  3226.   else
  3227.     return (FS_EXISTS);
  3228. #else /* !AFS */
  3229.  
  3230.   /* Find out if the file is actually executable.  By definition, the
  3231.      only other criteria is that the file has an execute bit set that
  3232.      we can use. */
  3233.   if (user_id == -1)
  3234.     user_id = current_user.euid;
  3235.  
  3236.   /* Root only requires execute permission for any of owner, group or
  3237.      others to be able to exec a file. */
  3238.   if (user_id == 0)
  3239.     {
  3240.       int bits;
  3241.  
  3242.       bits = (u_mode_bits (finfo.st_mode) |
  3243.           g_mode_bits (finfo.st_mode) |
  3244.           o_mode_bits (finfo.st_mode));
  3245.  
  3246.       if (X_BIT (bits))
  3247.     return (FS_EXISTS | FS_EXECABLE);
  3248.     }
  3249.  
  3250.   /* If we are the owner of the file, the owner execute bit applies. */
  3251.   if (user_id == finfo.st_uid && X_BIT (u_mode_bits (finfo.st_mode)))
  3252.     return (FS_EXISTS | FS_EXECABLE);
  3253.  
  3254.   /* If we are in the owning group, the group permissions apply. */
  3255.   if (group_member (finfo.st_gid) && X_BIT (g_mode_bits (finfo.st_mode)))
  3256.     return (FS_EXISTS | FS_EXECABLE);
  3257.  
  3258.   /* If `others' have execute permission to the file, then so do we,
  3259.      since we are also `others'. */
  3260.   if (X_BIT (o_mode_bits (finfo.st_mode)))
  3261.     return (FS_EXISTS | FS_EXECABLE);
  3262.   else
  3263.     return (FS_EXISTS);
  3264. #endif /* !AFS */
  3265. }
  3266.  
  3267. /* Return non-zero if FILE exists and is executable.
  3268.    Note that this function is the definition of what an
  3269.    executable file is; do not change this unless YOU know
  3270.    what an executable file is. */
  3271. int
  3272. executable_file (file)
  3273.      char *file;
  3274. {
  3275.   return (file_status (file) & FS_EXECABLE);
  3276. }
  3277.  
  3278. /* DOT_FOUND_IN_SEARCH becomes non-zero when find_user_command ()
  3279.    encounters a `.' as the directory pathname while scanning the
  3280.    list of possible pathnames; i.e., if `.' comes before the directory
  3281.    containing the file of interest. */
  3282. int dot_found_in_search = 0;
  3283.  
  3284. /* Locate the executable file referenced by NAME, searching along
  3285.    the contents of the shell PATH variable.  Return a new string
  3286.    which is the full pathname to the file, or NULL if the file
  3287.    couldn't be found.  If a file is found that isn't executable,
  3288.    and that is the only match, then return that. */
  3289. char *
  3290. find_user_command (name)
  3291.      char *name;
  3292. {
  3293.   return (find_user_command_internal (name, FS_EXEC_PREFERRED));
  3294. }
  3295.  
  3296. /* Locate the file referenced by NAME, searching along the contents
  3297.    of the shell PATH variable.  Return a new string which is the full
  3298.    pathname to the file, or NULL if the file couldn't be found.  This
  3299.    returns the first file found. */
  3300. char *
  3301. find_path_file (name)
  3302.      char *name;
  3303. {
  3304.   return (find_user_command_internal (name, FS_EXISTS));
  3305. }
  3306.  
  3307. static char *
  3308. find_user_command_internal (name, flags)
  3309.      char *name;
  3310.      int flags;
  3311. {
  3312.   char *path_list = (char *)NULL;
  3313.   SHELL_VAR *var;
  3314.  
  3315.   /* Search for the value of PATH in both the temporary environment, and
  3316.      in the regular list of variables. */
  3317.   if (var = find_variable_internal ("PATH", 1))
  3318.     path_list = value_cell (var);
  3319.  
  3320.   if (!path_list)
  3321.     return (savestring (name));
  3322.  
  3323.   return (find_user_command_in_path (name, path_list, flags));
  3324. }
  3325.  
  3326. /* Return the next element from PATH_LIST, a colon separated list of
  3327.    paths.  PATH_INDEX_POINTER is the address of an index into PATH_LIST;
  3328.    the index is modified by this function.
  3329.    Return the next element of PATH_LIST or NULL if there are no more. */
  3330. static char *
  3331. get_next_path_element (path_list, path_index_pointer)
  3332.      char *path_list;
  3333.      int *path_index_pointer;
  3334. {
  3335.   char *path;
  3336.  
  3337.   path = extract_colon_unit (path_list, path_index_pointer);
  3338.  
  3339.   if (!path)
  3340.     return (path);
  3341.  
  3342.   if (!*path)
  3343.     {
  3344.       free (path);
  3345.       path = savestring (".");
  3346.     }
  3347.  
  3348.   return (path);
  3349. }
  3350.  
  3351. char *
  3352. user_command_matches (name, flags, state)
  3353.      char *name;
  3354.      int flags, state;
  3355. {
  3356.   register int i;
  3357.   char *path_list;
  3358.   int  path_index;
  3359.   char *path_element;
  3360.   char *match;
  3361.   static char **match_list = NULL;
  3362.   static int match_list_size = 0;
  3363.   static int match_index = 0;
  3364.  
  3365.   if (!state)
  3366.     {
  3367.       /* Create the list of matches. */
  3368.       if (!match_list)
  3369.     {
  3370.       match_list =
  3371.         (char **) xmalloc ((match_list_size = 5) * sizeof(char *));
  3372.  
  3373.       for (i = 0; i < match_list_size; i++)
  3374.         match_list[i] = 0;
  3375.     }
  3376.  
  3377.       /* Clear out the old match list. */
  3378.       for (i = 0; i < match_list_size; i++)
  3379.     match_list[i] = NULL;
  3380.  
  3381.       /* We haven't found any files yet. */
  3382.       match_index = 0;
  3383.  
  3384.       path_list = get_string_value ("PATH");
  3385.       path_index = 0;
  3386.  
  3387.       while (path_list && path_list[path_index])
  3388.     {
  3389.       path_element = get_next_path_element (path_list, &path_index);
  3390.  
  3391.       if (!path_element)
  3392.         break;
  3393.  
  3394.       match = find_user_command_in_path (name, path_element, flags);
  3395.  
  3396.       free (path_element);
  3397.  
  3398.       if (!match)
  3399.         continue;
  3400.  
  3401.       if (match_index + 1 == match_list_size)
  3402.         match_list = (char **)xrealloc
  3403.           (match_list, ((match_list_size += 10) + 1) * sizeof (char *));
  3404.       match_list[match_index++] = match;
  3405.       match_list[match_index] = (char *)NULL;
  3406.     }
  3407.  
  3408.       /* We haven't returned any strings yet. */
  3409.       match_index = 0;
  3410.     }
  3411.  
  3412.   match = match_list[match_index];
  3413.  
  3414.   if (match)
  3415.     match_index++;
  3416.  
  3417.   return (match);
  3418. }
  3419.  
  3420. /* Return 1 if PATH1 and PATH2 are the same file.  This is kind of
  3421.    expensive.  If non-NULL STP1 and STP2 point to stat structures
  3422.    corresponding to PATH1 and PATH2, respectively. */
  3423. int
  3424. same_file (path1, path2, stp1, stp2)
  3425.      char *path1, *path2;
  3426.      struct stat *stp1, *stp2;
  3427. {
  3428.   struct stat st1, st2;
  3429.  
  3430.   if (stp1 == NULL)
  3431.     {
  3432.       if (stat (path1, &st1) != 0)
  3433.     return (0);
  3434.       stp1 = &st1;
  3435.     }
  3436.  
  3437.   if (stp2 == NULL)
  3438.     {
  3439.       if (stat (path2, &st2) != 0)
  3440.     return (0);
  3441.       stp2 = &st2;
  3442.     }
  3443.  
  3444.   return ((stp1->st_dev == stp2->st_dev) && (stp1->st_ino == stp2->st_ino));
  3445. }
  3446.  
  3447. /* Turn PATH, a directory, and NAME, a filename, into a full pathname.
  3448.    This allocates new memory and returns it. */
  3449. static char *
  3450. make_full_pathname (path, name, name_len)
  3451.      char *path, *name;
  3452.      int name_len;
  3453. {
  3454.   char *full_path;
  3455.   int path_len;
  3456.  
  3457.   path_len = strlen (path);
  3458.   full_path = xmalloc (2 + path_len + name_len);
  3459.   strcpy (full_path, path);
  3460.   full_path[path_len] = '/';
  3461.   strcpy (full_path + path_len + 1, name);
  3462.   return (full_path);
  3463. }
  3464.   
  3465. /* This does the dirty work for find_path_file () and find_user_command ().
  3466.    NAME is the name of the file to search for.
  3467.    PATH_LIST is a colon separated list of directories to search.
  3468.    FLAGS contains bit fields which control the files which are eligible.
  3469.    Some values are:
  3470.       FS_EXEC_ONLY:        The file must be an executable to be found.
  3471.       FS_EXEC_PREFERRED:    If we can't find an executable, then the
  3472.                 the first file matching NAME will do.
  3473.       FS_EXISTS:        The first file found will do.
  3474. */
  3475. static char *
  3476. find_user_command_in_path (name, path_list, flags)
  3477.      char *name;
  3478.      char *path_list;
  3479.      int flags;
  3480. {
  3481.   char *full_path, *path, *file_to_lose_on;
  3482.   int status, path_index, name_len;
  3483.   struct stat finfo;
  3484.  
  3485.   name_len = strlen (name);
  3486.  
  3487.   /* The file name which we would try to execute, except that it isn't
  3488.      possible to execute it.  This is the first file that matches the
  3489.      name that we are looking for while we are searching $PATH for a
  3490.      suitable one to execute.  If we cannot find a suitable executable
  3491.      file, then we use this one. */
  3492.   file_to_lose_on = (char *)NULL;
  3493.  
  3494.   /* We haven't started looking, so we certainly haven't seen
  3495.      a `.' as the directory path yet. */
  3496.   dot_found_in_search = 0;
  3497.  
  3498.   if (absolute_program (name))
  3499.     {
  3500.       full_path = xmalloc (1 + name_len);
  3501.       strcpy (full_path, name);
  3502.  
  3503.       status = file_status (full_path);
  3504.  
  3505.       /* If the file doesn't exist, quit now. */
  3506.       if (!(status & FS_EXISTS))
  3507.     {
  3508.       free (full_path);
  3509.       return ((char *)NULL);
  3510.     }
  3511.  
  3512.       /* If we only care about whether the file exists or not, return
  3513.      this filename. */
  3514.       if (flags & FS_EXISTS)
  3515.     return (full_path);
  3516.  
  3517.       /* Otherwise, maybe we care about whether this file is executable.
  3518.      If it is, and that is what we want, return it. */
  3519.       if ((flags & FS_EXEC_ONLY) && (status & FS_EXECABLE))
  3520.     return (full_path);
  3521.       else
  3522.     {
  3523.       free (full_path);
  3524.       return ((char *)NULL);
  3525.     }
  3526.     }
  3527.  
  3528.   /* Find out the location of the current working directory. */
  3529.   stat (".", &finfo);
  3530.  
  3531.   path_index = 0;
  3532.   while (path_list && path_list[path_index])
  3533.     {
  3534.       /* Allow the user to interrupt out of a lengthy path search. */
  3535.       QUIT;
  3536.  
  3537.       path = get_next_path_element (path_list, &path_index);
  3538.  
  3539.       if (!path)
  3540.     break;
  3541.  
  3542.       if (*path == '~')
  3543.     {
  3544.       char *t = tilde_expand (path);
  3545.       free (path);
  3546.       path = t;
  3547.     }
  3548.  
  3549.       /* Remember the location of "." in the path, in all its forms
  3550.      (as long as they begin with a `.', e.g. `./.') */
  3551.       if (!dot_found_in_search && (*path == '.') &&
  3552.       same_file (".", path, &finfo, (struct stat *)NULL))
  3553.     dot_found_in_search = 1;
  3554.  
  3555.       full_path = make_full_pathname (path, name, name_len);
  3556.       free (path);
  3557.  
  3558.       status = file_status (full_path);
  3559.  
  3560.       if (!(status & FS_EXISTS))
  3561.     goto next_file;
  3562.  
  3563.       /* The file exists.  If the caller simply wants the first file,
  3564.      here it is. */
  3565.       if (flags & FS_EXISTS)
  3566.     return (full_path);
  3567.  
  3568.        /* If the file is executable, then it satisfies the cases of
  3569.       EXEC_ONLY and EXEC_PREFERRED.  Return this file unconditionally. */
  3570.       if (status & FS_EXECABLE)
  3571.     {
  3572.       FREE (file_to_lose_on);
  3573.  
  3574.       return (full_path);
  3575.     }
  3576.  
  3577.       /* The file is not executable, but it does exist.  If we prefer
  3578.      an executable, then remember this one if it is the first one
  3579.      we have found. */
  3580.       if (flags & FS_EXEC_PREFERRED)
  3581.     {
  3582.       if (!file_to_lose_on)
  3583.         file_to_lose_on = savestring (full_path);
  3584.     }
  3585.  
  3586.     next_file:
  3587.       free (full_path);
  3588.     }
  3589.  
  3590.   /* We didn't find exactly what the user was looking for.  Return
  3591.      the contents of FILE_TO_LOSE_ON which is NULL when the search
  3592.      required an executable, or non-NULL if a file was found and the
  3593.      search would accept a non-executable as a last resort. */
  3594.   return (file_to_lose_on);
  3595. }
  3596.  
  3597. /* Given a string containing units of information separated by colons,
  3598.    return the next one pointed to by (P_INDEX), or NULL if there are no more.
  3599.    Advance (P_INDEX) to the character after the colon. */
  3600. char *
  3601. extract_colon_unit (string, p_index)
  3602.      char *string;
  3603.      int *p_index;
  3604. {
  3605.   int i, start;
  3606.  
  3607.   i = *p_index;
  3608.  
  3609.   if (!string || (i >= (int)strlen (string)))
  3610.     return ((char *)NULL);
  3611.  
  3612.   /* Each call to this routine leaves the index pointing at a colon if
  3613.      there is more to the path.  If I is > 0, then increment past the
  3614.      `:'.  If I is 0, then the path has a leading colon.  Trailing colons
  3615.      are handled OK by the `else' part of the if statement; an empty
  3616.      string is returned in that case. */
  3617.   if (i && string[i] == ':')
  3618.     i++;
  3619.  
  3620.   start = i;
  3621.  
  3622.   while (string[i] && string[i] != ':') i++;
  3623.  
  3624.   *p_index = i;
  3625.  
  3626.   if (i == start)
  3627.     {
  3628.       if (string[i])
  3629.     (*p_index)++;
  3630.  
  3631.       /* Return "" in the case of a trailing `:'. */
  3632.       return (savestring (""));
  3633.     }
  3634.   else
  3635.     {
  3636.       char *value;
  3637.  
  3638.       value = xmalloc (1 + i - start);
  3639.       strncpy (value, string + start, i - start);
  3640.       value [i - start] = '\0';
  3641.  
  3642.       return (value);
  3643.     }
  3644. }
  3645.  
  3646. /* Return non-zero if the characters from SAMPLE are not all valid
  3647.    characters to be found in the first line of a shell script.  We
  3648.    check up to the first newline, or SAMPLE_LEN, whichever comes first.
  3649.    All of the characters must be printable or whitespace. */
  3650.  
  3651. #if !defined (isspace)
  3652. #define isspace(c) ((c) == ' ' || (c) == '\t' || (c) == '\n' || (c) == '\f')
  3653. #endif
  3654.  
  3655. #if !defined (isprint)
  3656. #define isprint(c) (isletter(c) || digit(c) || ispunct(c))
  3657. #endif
  3658.  
  3659. int
  3660. check_binary_file (sample, sample_len)
  3661.      unsigned char *sample;
  3662.      int sample_len;
  3663. {
  3664.   register int i;
  3665.  
  3666.   for (i = 0; i < sample_len; i++)
  3667.     {
  3668.       if (sample[i] == '\n')
  3669.     break;
  3670.  
  3671.       if (!isspace (sample[i]) && !isprint (sample[i]))
  3672.     return (1);
  3673.     }
  3674.   return (0);
  3675. }
  3676.